source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
python_sharegpt_23k | 1,271 | Write a Python function to sort a given array of numbers in descending order using the quicksort algorithm. The function should be able to handle arrays with duplicate numbers, negative numbers, and floating-point numbers. The input array may contain up to 100,000 elements. The function should not use built-in sorting ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def quicksort_descending(arr: List[float]) -> List[float]:
"""
Sorts the given array of numbers in descending order using the quicksort algorithm.
Args:
arr (List[float]): The array of numbe... |
python_sharegpt_23k | 1,272 | Write a Python function to return a new array containing only the unique elements of the input array, sorted in ascending order. The function must implement the sorting and duplicate removal without using any built-in sorting or duplicate removal functions or methods.
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 unique_sorted_array(arr: List[int]) -> List[int]:
"""
Returns a new array containing only the unique elements of the input array, sorted in ascending order.
Args:
arr (List[int]): The in... |
python_sharegpt_23k | 1,273 | Write a Python function to calculate the number of times each word appears in a given string, where the string can contain punctuation marks and the word must be matched exactly (case-sensitive). The function should return a dictionary where the keys are the unique words found in the string and the values are the numbe... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def word_count(string: str) -> Dict[str, int]:
"""
Calculate the number of times each word appears in a given string, ignoring punctuation and words less than 3 characters long.
Args:
string... |
python_sharegpt_23k | 1,290 | Write a Python function that calculates the square of a given positive integer using only bitwise operations. The function should not use the multiplication operator, looping constructs, or conditional statements. The time complexity of the solution should be O(log n), where n is the input number, and the space complex... | Here is the Python code to solve the given problem in the markdown block:
```python
def square_number(n: int) -> int:
"""
Calculate the square of a given positive integer using only bitwise operations.
Args:
n (int): The positive integer to be squared.
Returns:
int: The square of the i... |
python_sharegpt_23k | 1,291 | Write a Python function to generate a list of `n` random integers within a specified range `[lower_limit, upper_limit]`. The function should be efficient and handle large values of `n` and wide ranges. The code should start with:
```python
from typing import List
import random
def generate_random_numbers(n: int, lower... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
def generate_random_numbers(n: int, lower_limit: int, upper_limit: int) -> List[int]:
"""
Generates a list of `n` random integers within the specified range `[lower_limit, upper_limit]`.
... |
python_sharegpt_23k | 1,293 | Write a Python function to modify a list of strings according to the following requirements:
1. Replace all empty strings with a default value.
2. Remove all duplicate strings.
3. Sort the final list in alphabetical order.
The function should start with:
```python
from typing import List
def modify_list(strings: List... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def modify_list(strings: List[str], default_value: str) -> List[str]:
"""
Modifies a list of strings by replacing empty strings with a default value,
removing duplicates, and sorting the list in alph... |
python_sharegpt_23k | 1,294 | Write a Python function to reverse the order of characters in a given string without using any built-in string reversal functions or libraries. The function should handle strings with special characters and whitespace, and should preserve the original case of each character. The input string will only contain ASCII cha... | Here is the Python code to solve the given problem in the markdown block:
```python
def reverse_string(string: str) -> str:
"""
Reverses the order of characters in a given string without using built-in string reversal functions or libraries.
The function preserves the original case of each character and han... |
python_sharegpt_23k | 1,296 | Write a Python function to find the sum of all prime numbers in a given list of integers and append this sum to the list. The function should return the modified list. The code should start with:
```python
from typing import List
def sum_of_primes_and_append(numbers: List[int]) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def is_prime(num: int) -> bool:
"""
Helper function to check if a number is prime.
Args:
num (int): The number to check for primality.
Returns:
bool: True if the number is prime... |
python_sharegpt_23k | 1,308 | Write a Python function to find the n-th Fibonacci number for a given n, using an iterative approach. The function should handle negative values of n and return an error message if the input is invalid. The function should have a time complexity of O(n) and space complexity of O(1). Additionally, the function should be... | Here is the Python code to solve the given problem in the markdown block:
```python
def fibonacci(n: int) -> int:
"""
Calculate the n-th Fibonacci number using an iterative approach.
Args:
n (int): The position in the Fibonacci sequence to calculate.
Returns:
int: The n-th Fibonacci nu... |
python_sharegpt_23k | 1,318 | Write a Python function to find the mode and median of numbers that are multiples of 3 and less than 100 from a given list of positive integers. The mode should be unique, and in case of multiple modes, choose the one with the highest frequency. If there are no numbers that satisfy the criteria, return `None` for both ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Optional
def find_mode_and_median(numbers: List[int]) -> Tuple[Optional[int], Optional[int]]:
"""
Find the mode and median of numbers that are multiples of 3 and less than 100 from a given list o... |
python_sharegpt_23k | 1,320 | Write a Python function to prefill an array with a given value. The array should have a specified length. 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 prefill_array(value: any, length: int) -> List[any]:
```
| Here is the Python code to solve the given problem in the markdown block:
:
```python
from typing import List
def prefill_array(value: any, length: int) -> List[any]:
"""
Prefills an array with a given value up to the specified length.
Args:
value (any): The value to fill the array with.
l... |
python_sharegpt_23k | 1,323 | Write a Python function to remove all occurrences of a target integer from a given list of integers while preserving the order of the remaining elements. The function should use only constant space complexity and should modify the list in place. 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_target_elements(nums: List[int], target: int) -> List[int]:
"""
Removes all occurrences of the target integer from the given list while preserving the order of the remaining elements.
The ... |
python_sharegpt_23k | 1,326 | Write a Python function to sort an array of numbers in descending order under the following conditions:
1. The array may contain both positive and negative numbers.
2. The array may contain floating-point numbers.
3. The function should be implemented using only a single loop, without using any built-in sorting algorit... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sort_array_descending(arr: List[float]) -> List[float]:
"""
Sorts an array of numbers in descending order using a single loop with nested iterations.
Args:
arr (List[float]): The array o... |
python_sharegpt_23k | 1,328 | Write a Python function to reverse the order of words in a given string while preserving the original string and handling edge cases. The function should not use any built-in Python functions that directly perform the word reversal operation, such as `string.split()` or `string.join()`. The function should raise a `Typ... | Here is the Python code to solve the given problem in the markdown block:
```python
def reverse_words(string: str) -> str:
"""
Reverses the order of words in a given string while preserving the original string.
Args:
string (str): The input string from which the words need to be reversed.
Retu... |
python_sharegpt_23k | 1,329 | Write a Python function to sort a given list of integers in ascending order using the Merge Sort algorithm. The function should ensure a time complexity of O(n log n) and maintain the stability of the sorting algorithm. The function should not use any built-in sorting functions or libraries.
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 merge_sort(lst: List[int]) -> List[int]:
"""
Sorts a given list of integers in ascending order using the Merge Sort algorithm.
Args:
lst (List[int]): The list of integers to be sorted.
... |
python_sharegpt_23k | 1,330 | Write a Python function to reverse the order of a list without using the built-in reverse function, any additional list or array for temporary storage, recursion, or any built-in string manipulation functions. Additionally, your solution should have a time complexity of O(n), where n is the length of the list.
The cod... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def reverse_list(lst: List[int]) -> None:
"""
Reverses the order of the given list in place without using additional storage, recursion, or built-in functions.
Args:
lst (List[int]): The lis... |
python_sharegpt_23k | 1,331 | Write a Python function called `swap_values` that takes in two variables as arguments and swaps their values. The function should return the updated values of the variables after the swap. However, you are not allowed to use any arithmetic operators, temporary variables, or built-in swap functions. Your implementation ... | Here is the Python code to solve the given problem in the markdown block:
```python
def swap_values(a: int, b: int) -> tuple:
"""
Swaps the values of two integers using bitwise XOR operations.
Args:
a (int): The first integer.
b (int): The second integer.
Returns:
tuple: A tupl... |
python_sharegpt_23k | 1,333 | Write a Python function that takes one argument as an array of integers and returns the sum of all the positive integers in the array. The function should ignore any negative integers and any duplicates in the array. Additionally, the function should validate the input to ensure it is a valid array of integers and rais... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
class InvalidInputException(Exception):
"""Custom exception for invalid input."""
pass
def sum_of_positive_integers(arr: List[int]) -> int:
"""
Calculate the sum of all positive integers in the ... |
python_sharegpt_23k | 1,338 | Write a Python function to compute the factorial of a given non-negative integer using an iterative approach. The function should not use recursion or any built-in mathematical functions such as `math.factorial()`. Instead, it should use a loop to calculate the factorial. The code should start with:
```python
def compu... | Here is the Python code to solve the given problem in the markdown block:
```python
def compute_factorial(n: int) -> int:
"""
Compute the factorial of a given non-negative integer using an iterative approach.
Args:
n (int): The non-negative integer for which to compute the factorial.
Returns:
... |
python_sharegpt_23k | 1,346 | Write a Python function to implement a stable sorting algorithm that sorts a list of integers in ascending order with a time complexity of O(n log n). Additionally, write a function to check if a list of integers is sorted in ascending order with a time complexity of O(n). The sorting algorithm should not use the built... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def merge_sort(arr: List[int]) -> List[int]:
"""
Sorts a list of integers in ascending order using the merge sort algorithm.
Args:
arr (List[int]): The list of integers to be sorted.
Re... |
python_sharegpt_23k | 1,349 | Write a Python function to convert a given decimal number to its binary representation without using any built-in functions or libraries for number conversion. The solution must ensure a time complexity of O(log n), where n is the given decimal number. Additionally, the function should correctly handle the reversal of ... | Here is the Python code to solve the given problem in the markdown block:
```python
def decimal_to_binary(n: int) -> str:
"""
Converts a given decimal number to its binary representation without using any built-in functions or libraries.
Args:
n (int): The decimal number to be converted.
Retur... |
python_sharegpt_23k | 1,363 | Write a Python function to calculate the sum of the absolute values of the elements in two given arrays of integers. The function should handle arrays with both positive and negative integers. The sum of the elements in each array will not exceed \(10^6\). The function should return `-1` if either of the arrays is empt... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_of_absolute_values(array1: List[int], array2: List[int]) -> int:
"""
Calculate the sum of the absolute values of the elements in two given arrays of integers.
Args:
array1 (List[int]... |
python_sharegpt_23k | 1,364 | Write a Python function to transpose a given two-dimensional array and handle specific edge cases. The function should:
1. Return an empty array if the input array is empty.
2. Return an empty array if the input array contains any non-numeric values.
3. Convert any negative numbers in the input array to their absolute ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def transpose_array(arr: List[List[int]]) -> List[List[int]]:
"""
Transposes a given two-dimensional array and handles specific edge cases.
Args:
arr (List[List[int]]): The input two-dimensi... |
python_sharegpt_23k | 1,367 | Write a Python function to compare two lists of objects and determine if they are equivalent based on specific criteria. The function should return `True` if the objects in both lists have the same `id` and `name` attributes, considering the order of the objects. Additionally, if an object in `list1` has a `name` attri... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, NamedTuple
class Object(NamedTuple):
id: int
name: str
def compare_lists(list1: List[Object], list2: List[Object]) -> bool:
"""
Compare two lists of objects and return True if they are equivale... |
python_sharegpt_23k | 1,368 | Write a Python function to perform a specified operation on a nested dictionary structure. The function should handle nested dictionaries, ensure that the original dictionary is not modified, and implement error handling for invalid keys or values. The function should also optimize the code to have a time complexity of... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Union
import copy
def perform_nested_operation(dictionary: Dict[str, Union[dict, str, int, float]], operation: str) -> Dict[str, Union[dict, str, int, float]]:
"""
Perform a specified operation on a nes... |
python_sharegpt_23k | 1,375 | Write a Python function to implement the merge sort algorithm. The function should take a list of integers as input and return the sorted list. The code should start with:
```python
from typing import List
def merge_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 merge_sort(arr: List[int]) -> List[int]:
"""
Sorts a list of integers using the merge sort algorithm.
Args:
arr (List[int]): The list of integers to be sorted.
Returns:
List... |
python_sharegpt_23k | 1,384 | Write a Python function to check if two variables have the same type and, if applicable, the same length or keys. The function should also handle nested data structures, where lists or dictionaries may be nested within each other, and perform the same type and length checks for all nested elements. The function should ... | Here is the Python code to solve the given problem in the markdown block:
```python
def check_type_and_structure(var1, var2) -> bool:
"""
Check if two variables have the same type and, if applicable, the same length or keys.
The function also handles nested data structures.
Args:
var1: The firs... |
python_sharegpt_23k | 1,387 | Write a Python function to find the smallest prime factor of a given positive integer. The function should handle numbers up to \(10^{12}\) efficiently and return the smallest prime factor of the number. If the number is prime, the function should return the number itself.
The code should start with:
```python
import ... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def smallest_prime_factor(num: int) -> int:
"""
Find the smallest prime factor of a given positive integer.
Args:
num (int): The positive integer for which to find the smallest prime factor.
Return... |
python_sharegpt_23k | 1,392 | Write a Python function to count the occurrences of each element in a given array of integers, ensuring that the function removes any duplicate elements before counting. The function should be implemented with a time complexity of O(n) and a space complexity of O(n). Additionally, the function should not use any built-... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def count_elements(arr: List[int]) -> Dict[int, int]:
"""
Counts the occurrences of each element in the given array after removing duplicates.
Args:
arr (List[int]): The array of integ... |
python_sharegpt_23k | 1,393 | Write a Python function to remove duplicate elements from a given array of integers, sort the array in descending order, and return both the sorted array and the sum of its elements. The function should handle negative numbers and zero appropriately.
The code should start with:
```python
from typing import List, Tuple... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def remove_duplicates_and_sort(arr: List[int]) -> Tuple[List[int], int]:
"""
Removes duplicate elements from the given array, sorts the array in descending order,
and returns both the sorted a... |
python_sharegpt_23k | 1,397 | Write a Python function to find the first and last index of a given element in a sorted array (in descending order) that may contain duplicates. If the element is not found, return `[-1, -1]`. The function should use a binary search approach to efficiently locate the first and last occurrences of the target element.
T... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_first_last_index(arr: List[int], target: int) -> List[int]:
"""
Find the first and last index of a given element in a sorted array (in descending order) that may contain duplicates.
Args:
... |
python_sharegpt_23k | 1,399 | Write a Python function to generate a random number within a specified range. The function should accept two parameters: `min_value` and `max_value`, which define the lower and upper bounds of the range, respectively. The function should return the generated random number.
The code should start with:
```python
import ... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
def generate_random_number(min_value: int, max_value: int) -> int:
"""
Generates a random integer within the specified range [min_value, max_value].
Args:
min_value (int): The lower bound of the range... |
python_sharegpt_23k | 1,400 | Write a Python function to determine if two given strings are anagrams of each other. The function should handle strings that contain spaces, punctuation marks, and digits. Additionally, the function should be case-insensitive. The code should start with:
```python
def are_anagrams(str1: str, str2: str) -> bool:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def are_anagrams(str1: str, str2: str) -> bool:
"""
Determine if two given strings are anagrams of each other.
Args:
str1 (str): The first string to compare.
str2 (str): The second string to compare.
Re... |
python_sharegpt_23k | 1,401 | Write a Python function to merge two dictionaries into another dictionary, ensuring that the merged dictionary only contains key-value pairs where the key is a string and the value is a positive integer that is divisible by 3. If a key-value pair in either `dict1` or `dict2` does not meet this requirement, it should be... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def merge_dictionaries(dict1: Dict[str, int], dict2: Dict[str, int]) -> Dict[str, int]:
"""
Merge two dictionaries into another dictionary, ensuring that the merged dictionary
only contains key-value... |
python_sharegpt_23k | 1,403 | Write a Python function that calculates the sum of a list of numbers, rounded to the nearest whole number. The function should only perform the calculation if all the numbers in the list are positive integers. If any number in the list is negative or non-integer, the function should raise a `ValueError` with an appropr... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_sum_of_positive_integers(numbers: List[int]) -> int:
"""
Calculate the sum of a list of positive integers, rounded to the nearest whole number.
Args:
numbers (List[int]): A... |
python_sharegpt_23k | 1,410 | Write a Python function to calculate the median of a given array of integers without using any built-in functions or libraries that directly calculate the median. The function should handle edge cases such as empty arrays and arrays containing only negative numbers. The median should be rounded to two decimal places.
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_median(arr: List[int]) -> float:
"""
Calculate the median of a given array of integers without using built-in functions or libraries.
Args:
arr (List[int]): The array of intege... |
python_sharegpt_23k | 1,416 | Write a Python function to recursively search for the last occurrence of a case-insensitive substring in a given string and return the index of its starting position. The function should ignore any leading and trailing whitespaces in both the substring and the string. Additionally, the function should handle the substr... | Here is the Python code to solve the given problem in the markdown block:
```python
def last_occurrence_recursive(string: str, substring: str) -> int:
"""
Recursively search for the last occurrence of a case-insensitive substring in a given string and return the index of its starting position.
The function ... |
python_sharegpt_23k | 1,418 | Write a Python function to create a dictionary with words and their corresponding counts of occurrences from a given string containing multiple sentences. The function should ignore case sensitivity and punctuation marks. Additionally, the function should exclude any words that are palindromes and have an odd number of... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
import re
def count_words(string: str) -> Dict[str, int]:
"""
Counts the occurrences of words in a given string, ignoring case sensitivity and punctuation marks.
Excludes words that are palindromes a... |
python_sharegpt_23k | 1,420 | Write a Python function to calculate the sum of corresponding elements from two given arrays of integers, handling arrays of different lengths, negative numbers, and decimal numbers. The resulting sum should be returned as an array. If the lengths of the arrays are not equal, the sum should only be calculated up to the... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_sum_of_arrays(a: List[int], b: List[int]) -> List[int]:
"""
Calculate the sum of corresponding elements from two given arrays of integers.
Args:
a (List[int]): The first array ... |
python_sharegpt_23k | 1,422 | Write a Python function to calculate the sum of all elements in a given list without using any built-in functions or operators for summation. Instead, implement your own algorithm to iterate through the list and calculate the sum manually. Additionally, you are not allowed to use any temporary variables or data structu... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def manual_sum(numbers: List[int]) -> int:
"""
Calculate the sum of all elements in the given list without using any built-in functions or operators for summation.
Args:
numbers (List[int]):... |
python_sharegpt_23k | 1,423 | Write a Python function to search for the first occurrence of a target element in a sorted list of integers. The function should return the index of the first occurrence of the target element if it is found in the list, and -1 if it is not found. The function should have a time complexity of O(log n), where n is the le... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def search_first_occurrence(arr: List[int], target: int) -> int:
"""
Searches for the first occurrence of a target element in a sorted list of integers.
Args:
arr (List[int]): A sorted list ... |
python_sharegpt_23k | 1,436 | Write a Python function to calculate the sum of the first n prime numbers. The function should handle cases where n is not a positive integer and return an appropriate error message. The function should also handle cases where n is a very large number (e.g., greater than 10^6) efficiently.
The code should start with:
... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def is_prime(num: int) -> bool:
"""
Check if a given number is prime.
Args:
num (int): The number to check for primality.
Returns:
bool: True if the number is prime, False otherwise.
""... |
python_sharegpt_23k | 1,441 | Write a Python function to extract and return a list of values from a given dictionary that are greater than 5 and less than 9. The values should be sorted in ascending order. The function should have a time complexity of O(n log n), where n is the total number of values in the dictionary.
The code should start with:
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, List
def extract_and_sort_values(dictionary: Dict[str, int]) -> List[int]:
"""
Extracts and returns a list of values from the given dictionary that are greater than 5 and less than 9, sorted in ascendin... |
python_sharegpt_23k | 1,449 | Write a Python function to generate the first n prime numbers using a segmented sieve algorithm. The function should be efficient and handle the case where n is a positive integer greater than 1 and less than or equal to 10^6. The code should start with:
```python
from typing import List
def generate_first_n_primes(n:... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import math
def generate_first_n_primes(n: int) -> List[int]:
"""
Generate the first n prime numbers using a segmented sieve algorithm.
Args:
n (int): The number of prime numbers to generate... |
python_sharegpt_23k | 1,454 | Write a Python function to find the intersection of two input arrays of integers. The intersection is defined as the set of elements that are common to both arrays. The order of elements in the output array does not matter, and the output array should not contain any duplicate elements. The function should not use any ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def array_intersection(array1: List[int], array2: List[int]) -> List[int]:
"""
Find the intersection of two arrays of integers.
Args:
array1 (List[int]): The first array of integers.
... |
python_sharegpt_23k | 1,457 | Write a Python function to count the number of times a specific word occurs in a given sentence, considering that the sentence may contain multiple occurrences of the same word in different cases. The function should be case-insensitive and should handle punctuation marks and special characters within words, considerin... | Here is the Python code to solve the given problem in the markdown block:
```python
def count_word_occurrences(sentence: str, word: str) -> int:
"""
Counts the number of times a specific word occurs in a given sentence, considering case-insensitivity and handling punctuation marks.
Args:
sentence (... |
python_sharegpt_23k | 1,460 | Write a Python function to calculate the nth Fibonacci number using an optimized recursive approach with memoization. The function should have a time complexity of O(n) and avoid redundant calculations by storing previously computed Fibonacci numbers in a dictionary.
The code should start with:
```python
def optimized... | Here is the Python code to solve the given problem in the markdown block:
```python
def optimized_fibonacci(num: int, memo: dict = None) -> int:
"""
Calculate the nth Fibonacci number using an optimized recursive approach with memoization.
Args:
num (int): The position in the Fibonacci sequence to ... |
python_sharegpt_23k | 1,466 | Write a Python function to calculate the factorial of a positive integer input. The function should return the factorial value, which is the product of all positive integers less than or equal to the input number. The function should only accept positive integer inputs. The factorial of 0 is defined as 1.
The code sho... | Here is the Python code to solve the given problem in the markdown block:
```python
def factorial(n: int) -> int:
"""
Calculate the factorial of a positive integer.
The factorial of a number n (denoted as n!) is the product of all positive integers
less than or equal to n. The factorial of 0 is defined... |
python_sharegpt_23k | 1,469 | Write a Python function to sort a given list of integers using a stable sorting algorithm with a time complexity of O(n log n) and a space complexity of O(1). The function should handle duplicate elements and maintain their relative order in the sorted list. The function should not use any built-in sorting functions or... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def custom_stable_sort(lst: List[int]) -> List[int]:
"""
Sorts a given list of integers using an in-place merge sort algorithm.
The algorithm maintains the relative order of duplicate elements and ha... |
python_sharegpt_23k | 1,474 | Write a Python function to calculate the sum of the digits of a given positive integer `n` without using any built-in functions for converting the integer to a string or manipulating strings. The function should have a time complexity of O(log n), where n is the given number, and should be able to handle integers up to... | Here is the Python code to solve the given problem in the markdown block:
```python
def sum_of_digits(n: int) -> int:
"""
Calculate the sum of the digits of a given positive integer `n`.
Args:
n (int): The positive integer whose digits' sum is to be calculated.
Returns:
int: The sum of... |
python_sharegpt_23k | 1,483 | Write a Python function to find and return all prime numbers within a given range `[start, end]`. The function should be efficient and correctly identify prime numbers using an optimized approach.
The code should start with:
```python
from typing import List
def find_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
import math
def find_primes_in_range(start: int, end: int) -> List[int]:
"""
Find and return all prime numbers within the given range [start, end].
Args:
start (int): The starting number of ... |
python_sharegpt_23k | 1,485 | Write a Python function to validate if a given string is a valid integer according to the following constraints:
- The string can be preceded by an optional positive or negative sign.
- The string can contain leading and trailing whitespaces.
- The string can only consist of digits.
- The string cannot exceed a length ... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_valid_integer(string: str) -> bool:
"""
Validates if a given string is a valid integer according to specified constraints.
Args:
string (str): The string to be validated.
Returns:
bool: True if t... |
python_sharegpt_23k | 1,488 | Write a Python function to filter out the prime numbers from a given list of integers. The function should return a new list containing only the prime numbers. The function should be able to handle negative integers as well, treating them the same as their positive counterparts when determining their primality. For exa... | 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:
"""
Determines if a given number is prime.
Args:
n (int): The number to check for primality.
Returns:
bool: True if the number is prime, False othe... |
python_sharegpt_23k | 1,500 | Write a Python function to sort a given list of numbers from smallest to largest without using any built-in sorting functions or libraries. The sorting algorithm must have a time complexity of O(n^2) and a space complexity of O(1). The function should modify the input list in place and return the sorted list.
The code... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def custom_sort(arr: List[int]) -> List[int]:
"""
Sorts a given list of numbers from smallest to largest using the selection sort algorithm.
The function modifies the input list in place and returns ... |
python_sharegpt_23k | 1,503 | Write a Python function to filter out the even numbers from a given list, remove any duplicates, and return the sorted list in descending order. The function should start with:
```python
from typing import List
def get_sorted_unique_even_numbers(nums: List[int]) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def get_sorted_unique_even_numbers(nums: List[int]) -> List[int]:
"""
Filters out the even numbers from the given list, removes duplicates, and returns the sorted list in descending order.
Args:
... |
python_sharegpt_23k | 1,504 | Write a Python function to transform a given list of integers into a dictionary. The dictionary should contain the numbers as keys and their cubes as values. The list should not contain any duplicates and should be sorted in descending order. The dictionary should only include numbers that are divisible by 3 and their ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def transform_list_to_dict(nums: List[int]) -> Dict[int, int]:
"""
Transforms a given list of integers into a dictionary. The dictionary contains the numbers as keys and their cubes as values.
... |
python_sharegpt_23k | 1,506 | Implement a breadth-first search (BFS) algorithm in Python that can handle a directed graph and return the shortest path between two given vertices. The algorithm should have a space complexity of O(n) and a time complexity of O(V + E), where V is the number of vertices and E is the number of edges in the graph. The co... | Here is the Python code to solve the given problem in the markdown block:
```python
from collections import deque
def bfs_shortest_path(graph, start, end):
"""
Find the shortest path between two vertices in a directed graph using Breadth-First Search (BFS).
Args:
graph (dict): A dictionary represe... |
python_sharegpt_23k | 1,509 | Write a Python function that takes two integer arguments and returns their sum. The function should handle cases where the input arguments are not integers by returning an error message. Additionally, the function should be able to handle negative integers as input. The function should only use basic arithmetic operati... | Here is the Python code to solve the given problem in the markdown block:
```python
def add_two_numbers(a, b) -> int or str:
"""
Adds two integers and returns their sum. If either input is not an integer, returns an error message.
Args:
a (int): The first integer to be added.
b (int): The s... |
python_sharegpt_23k | 1,514 | Write a Python function to convert a decimal number to its binary representation using only bitwise operators and without using any loops or recursion. The decimal number can be positive or negative. The function should handle both positive and negative integers, and return the binary representation as a string.
The c... | Here is the Python code to solve the given problem in the markdown block:
```python
def decimal_to_binary(decimal: int) -> str:
"""
Converts a decimal number to its binary representation using only bitwise operators.
Args:
decimal (int): The decimal number to convert.
Returns:
str: The... |
python_sharegpt_23k | 1,519 | Write a Python function to extract prime numbers from a given list of integers and return them in descending order. The function should have a time complexity of O(n), where n is the length of the original list. The code should start with:
```python
from typing import List
def get_descending_primes(original_list: List... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import math
def is_prime(num: int) -> bool:
"""
Check if a number is prime.
Args:
num (int): The number to check for primality.
Returns:
bool: True if the number is prime, False... |
python_sharegpt_23k | 1,520 | Write a Python function to check whether a list of integers contains at least one prime number. If a prime number is found, the function should print "Prime number found" and the number of iterations required to determine if each number in the list is prime. If a number is not prime, the function should print "Not a pr... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def check_for_primes(list_data: List[int]) -> None:
"""
Check whether the list contains a prime number and print the result along with the number of iterations required to determine if each number is pri... |
python_sharegpt_23k | 1,522 | Write a Python function to filter out all the prime numbers from a given list and return them in ascending order. The function should also remove any duplicate prime numbers from the filtered list. The code should start with:
```python
from typing import List
def filter_unique_primes(numbers: List[int]) -> List[int]:
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def filter_unique_primes(numbers: List[int]) -> List[int]:
"""
Filters out all unique prime numbers from the given list and returns them in ascending order.
Args:
numbers (List[int]): The li... |
python_sharegpt_23k | 1,529 | Write a Python function to determine if a given string is a palindrome using a recursive approach. The function should ignore case sensitivity and consider only alphanumeric characters. The function should have a time complexity of O(n) and a space complexity of O(1). The code should start with:
```python
def is_palind... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_palindrome_recursive(s: str) -> bool:
"""
Determine if a given string is a palindrome using a recursive approach.
This function checks if the string is a palindrome by ignoring case sensitivity
and considering on... |
python_sharegpt_23k | 1,535 | Write a Python function to calculate the result of multiplying a number `x` by itself `n` times using recursion. The function should handle negative values of `x` and `n` by returning an error message. Additionally, the function should use at least three recursive calls to solve the problem.
The code should start with... | Here is the Python code to solve the given problem in the markdown block:
```python
def recursive_multiplication(x: int, n: int) -> int:
"""
Calculate the result of multiplying a number `x` by itself `n` times using recursion.
Args:
x (int): The base number.
n (int): The exponent.
Retu... |
python_sharegpt_23k | 1,537 | Write a Python function to calculate the frequency of each number in a given list of integers and floating-point numbers. The function should return a dictionary where the keys are the numbers (with precision up to 2 decimal places for floating-point numbers) and the values are their respective frequencies. The functio... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def calculate_frequency(numbers: List[float]) -> Dict[str, int]:
"""
Calculate the frequency of each number in a given list of integers and floating-point numbers.
Args:
numbers (List[... |
python_sharegpt_23k | 1,538 | Write a Python function to find the two largest numbers in a given list of integers with a time complexity of O(n). The function should not use any built-in sorting functions or additional data structures to store intermediate values. It should only iterate through the list once and should not modify the original list.... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple, Union
def find_two_largest(numbers: List[int]) -> Union[Tuple[int, int], str]:
"""
Find the two largest numbers in a given list of integers with a time complexity of O(n).
Args:
numb... |
python_sharegpt_23k | 1,540 | Write a Python function to process a list of floating-point numbers, converting each element to an integer, sorting the list in descending order, and returning the sum of all elements in the sorted list. The function should handle the conversion and sorting efficiently and ensure that the original list is not modified.... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_float_list(x_data: List[float]) -> (List[int], int):
"""
Processes a list of floating-point numbers by converting each element to an integer,
sorting the list in descending order, and ret... |
python_sharegpt_23k | 1,543 | Write a Python function to perform the Caesar Cipher encryption on a given string of text using a specified key. The Caesar Cipher involves shifting each letter in the text by a certain number of positions down the alphabet. The function should handle both uppercase and lowercase letters, and non-alphabetical character... | Here is the Python code to solve the given problem in the markdown block:
```python
def caesar_cipher(text: str, key: int) -> str:
"""
Encrypts the given text using the Caesar Cipher technique with the specified key.
Args:
text (str): The text to be encrypted.
key (int): The number of posit... |
python_sharegpt_23k | 1,557 | Write a Python function to find the number of unique values in a given array of integers and return the modified array with duplicates removed, sorted in ascending order. The function should not use any additional data structures such as sets or dictionaries. 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
def remove_duplicates_and_count_unique(nums: List[int]) -> (int, List[int]):
"""
Find the number of unique values in the given array and return the modified array
with duplicates removed and sorted i... |
python_sharegpt_23k | 1,559 | Write a Python function to transform a list of integers and other values according to the following rules:
1. For each positive even number, append its square to the result list.
2. For each negative odd number, append its cube to the result list.
3. For the integer 0, append the string "zero" to the result list.
4. Fo... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def transform_list(nums: List[int]) -> List[str]:
"""
Transforms a list of integers and other values according to specific rules.
Args:
nums (List[int]): The list of integers and other value... |
python_sharegpt_23k | 1,561 | Write a Python function to print out all the elements of a given 2D array in a spiral order. The array can have varying dimensions, but it will always be a rectangular matrix (m x n). The spiral order starts from the top-left corner and goes clockwise.
The code should start with:
```python
from typing import List
def... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def print_spiral_order(matrix: List[List[int]]) -> None:
"""
Prints the elements of a given 2D array in a spiral order.
Args:
matrix (List[List[int]]): The 2D array to be printed in spiral o... |
python_sharegpt_23k | 1,562 | Write a Python function to calculate the sum of the elements in each row of a given 2-dimensional array. The array can have a variable number of rows and columns, and the elements are integers ranging from -10^9 to 10^9. The total number of elements in the array can be as large as 10^6. The sum of the elements in each ... | 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 the elements in each row of a given 2-dimensional array.
Args:
arr (List[List[int]]): A 2-dimensional array of integ... |
python_sharegpt_23k | 1,567 | Write a Python function to reverse a given string without using any built-in functions or libraries. You are only allowed to use basic data structures like strings, lists, and loops. Additionally, the solution should have a time complexity of O(n), where n is the length of the string.
The code should start with:
```py... | Here is the Python code to solve the given problem in the markdown block:
```python
def reverse_string(input_str: str) -> str:
"""
Reverses the given string without using any built-in functions or libraries.
Args:
input_str (str): The string to be reversed.
Returns:
str: The reversed s... |
python_sharegpt_23k | 1,569 | Write a Python function to generate a random hexadecimal string of a specified length, reverse the order of its characters, convert the reversed string to its binary representation, count the number of binary digits that are set to 1, and finally convert this count to its corresponding octal representation.
The code s... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
def hex_to_octal(length: int) -> str:
"""
Generate a random hexadecimal string of the specified length, reverse it,
convert the reversed string to binary, count the number of binary digits
that are set to ... |
python_sharegpt_23k | 1,579 | Write a Python function to calculate the nth Fibonacci number with a time complexity of O(n) and without using any additional data structures. The function should handle negative inputs by returning `None`. The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding ones.
The... | 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 with a time complexity of O(n) and without using additional data structures.
Args:
n (int): The index of the Fibonacci number to calculate.
R... |
python_sharegpt_23k | 1,583 | Write a Python function to calculate the weighted mean of a list of numbers, where each number is multiplied by a corresponding weight before calculating the mean. The weights are provided in a separate list, and the function should ensure that the weights list has a length equal to or greater than the numbers list. Th... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_weighted_mean(numbers: List[int], weights: List[float]) -> int:
"""
Calculate the weighted mean of a list of numbers, where each number is multiplied by a corresponding weight.
Args:
... |
python_sharegpt_23k | 1,590 | Write a Python function to calculate the sum of all numbers in a given array, which may contain nested arrays or dictionaries. The function should handle nested structures by using an iterative approach with a stack data structure instead of recursion.
The code should start with:
```python
from typing import Union, Li... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Union, List, Dict
def sum_nested_array(arr: Union[int, List, Dict]) -> int:
"""
Calculate the sum of all numbers in a given array, which may contain nested arrays or dictionaries.
Args:
arr (Unio... |
python_sharegpt_23k | 1,596 | Write a Python function to print all possible combinations of five different numbers from 1 to 20, such that the sum of the five numbers equals a given target value. The target value will be a random number between 30 and 60, inclusive. Ensure that the function correctly handles the constraint of having five different ... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
def print_combinations(target: int):
"""
Prints all possible combinations of five different numbers from 1 to 20 that sum up to the given target value.
Args:
target (int): The target sum value, which ... |
python_sharegpt_23k | 1,598 | Write a Python function to merge two sorted arrays of prime numbers in ascending order while removing duplicates and maintaining the original order of the elements. The merged array should have no more than twice the length of the original arrays. Additionally, the merged array should be sorted in descending order. The... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def merge_sorted_arrays(arr1: List[int], arr2: List[int]) -> List[int]:
"""
Merge two sorted arrays of prime numbers in ascending order while removing duplicates and maintaining the original order of the... |
python_sharegpt_23k | 1,602 | Write a Python function to calculate the sum of two numbers correctly. The function should handle both positive and negative integers. The code should start with:
```python
def calculate_sum(a: int, b: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
:
```python
def calculate_sum(a: int, b: int) -> int:
"""
Calculate the sum of two integers.
Args:
a (int): The first integer.
b (int): The second integer.
Returns:
int: The sum of the two integers.
"... |
python_sharegpt_23k | 1,606 | Write a Python function to combine two lists into a single list containing each element of both lists in order. The combined list should be sorted in ascending order and should not contain any duplicate elements. The solution should have a time complexity of O(n log n), where n is the total number of elements in both l... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def combine_and_sort_lists(list_first: List[int], list_second: List[int]) -> List[int]:
"""
Combines two lists into a single list containing each element of both lists in order.
The combined list is ... |
python_sharegpt_23k | 1,612 | Write a Python function to format the current date and time in the specified format "dd/mm/yyyy hh:mm:ss". The function should handle the conversion correctly and return the formatted string. Additionally, provide a piece of erroneous code that attempts to display the date and time in the incorrect format "mm/dd/yyyy h... | Here is the Python code to solve the given problem in the markdown block:
```python
import datetime
def format_current_datetime() -> str:
"""
Formats the current date and time in the specified format "dd/mm/yyyy hh:mm:ss".
Returns:
str: The formatted date and time string.
"""
# Get the cur... |
python_sharegpt_23k | 1,613 | Write a Python function to insert an integer into a sorted array of integers while maintaining the sorted order. The function should have a time complexity of O(log n) and a space complexity of O(1). The function should return the modified array.
The code should start with:
```python
from typing import List
def inser... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def insert_into_sorted_array(arr: List[int], num: int) -> List[int]:
"""
Inserts an integer into a sorted array of integers while maintaining the sorted order.
Args:
arr (List[int]): The sor... |
python_sharegpt_23k | 1,614 | Write a Python function called `classify_number` that takes an integer as an argument and returns the following classifications:
- "positive" if the value is greater than 0
- "negative" if the value is less than 0
- "zero" if the value is equal to 0
Additional Constraints:
- Your implementation of the function should ... | Here is the Python code to solve the given problem in the markdown block:
```python
def classify_number(num: int) -> str:
"""
Classify the given integer as "positive", "negative", or "zero" without using comparison operators or if-else statements.
Args:
num (int): The integer to classify.
Retu... |
python_sharegpt_23k | 1,618 | Write a Python function to reverse a list in place without using the `reverse()` method, without using any built-in Python functions or methods, and without creating a new list or using additional data structures. The function should have a time complexity of O(n), where n is the length of the input list.
The code sho... | 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]) -> List[int]:
"""
Reverses the given list in place without using the reverse() method,
built-in functions, or methods, and without creating a new list or
... |
python_sharegpt_23k | 1,619 | Write a Python function to generate an n x n identity matrix using nested loops. However, you are not allowed to use any if statements or logical operators such as AND, OR, NOT, etc. The function should return the generated matrix.
The code should start with:
```python
from typing import List
def generate_identity_ma... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_identity_matrix(n: int) -> List[List[int]]:
"""
Generate an n x n identity matrix.
Args:
n (int): The size of the identity matrix.
Returns:
List[List[int]]: The n x... |
python_sharegpt_23k | 1,634 | Write a Python function to sort an array of numbers in descending order using a modified version of the bubble sort algorithm. The function should have a time complexity of O(n^2) and a space complexity of O(1). The array may contain duplicate numbers and have a maximum length of 1000. The function should not use any a... | 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 numbers in descending order using a modified bubble sort algorithm.
Args:
arr (List[int]): The array of numbers... |
python_sharegpt_23k | 1,636 | Write a Python function to sort an array in descending order using a custom merge sort algorithm. The function should handle arrays with duplicate elements and ensure that the time complexity is O(n log n). The function should not use any built-in sorting functions or data structures.
The code should start with:
```py... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sort_descending(arr: List[int]) -> List[int]:
"""
Sorts the given array in descending order using a custom merge sort algorithm.
Args:
arr (List[int]): The array to be sorted.
Retur... |
python_sharegpt_23k | 1,638 | Write a Python function to determine the maximum of five numbers without using the built-in `max()` function and without using any conditional statements (if/else, switch, etc.). The function should take five integers as input and return the maximum value.
The code should start with:
```python
def find_maximum(num1: i... | Here is the Python code to solve the given problem in the markdown block:
```python
def find_maximum(num1: int, num2: int, num3: int, num4: int, num5: int) -> int:
"""
Determine the maximum of five numbers without using the built-in max() function
and without using any conditional statements.
Args:
... |
python_sharegpt_23k | 1,640 | Write a Python function to calculate the square root of a given non-negative integer `x` using a binary search algorithm. The function should have a time complexity of O(log n) and a space complexity of O(1). You are not allowed to use any built-in functions or libraries for calculating the square root, nor any mathema... | Here is the Python code to solve the given problem in the markdown block:
```python
def sqrt_binary_search(x: int) -> int:
"""
Calculate the integer part of the square root of a non-negative integer x using a binary search algorithm.
Args:
x (int): The non-negative integer for which to calculate th... |
python_sharegpt_23k | 1,642 | Write a Python function to sort a given array of integers in ascending order using the Merge Sort algorithm. The function should have a time complexity of O(n log n) and should not use any built-in sorting functions or libraries. The sorted array should be stored in a new array, and the original array should remain unc... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def merge_sort(array: List[int]) -> List[int]:
"""
Sorts a given array of integers in ascending order using the Merge Sort algorithm.
Args:
array (List[int]): The array of integers to be sor... |
python_sharegpt_23k | 1,647 | Write a Python function that processes a list of integers according to the following rules:
1. It should return a new list containing only the even numbers from the original list.
2. The resulting list should not contain any duplicates.
3. The resulting list should be sorted in descending order.
4. If the original list... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_list(lst: List[int]) -> List[int]:
"""
Processes a list of integers to return a new list containing only the even numbers,
with duplicates removed and sorted in descending order. Raises a... |
python_sharegpt_23k | 1,650 | Write a Python function to iterate through the elements of an array and print the indices of elements that are within a specified range. The function should only consider elements that are greater than or equal to a given lower bound and less than or equal to a given upper bound. The time complexity of the solution sho... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def print_indices_in_range(arr: List[int], lower_bound: int, upper_bound: int) -> None:
"""
Iterates through the elements of an array and prints the indices of elements that are within a specified range.... |
python_sharegpt_23k | 1,652 | Write a Python function to filter and square the values of a dictionary, ensuring that only positive integer values are considered. The function should return a new dictionary with the same keys but with the values squared. The function should handle cases where the input dictionary is empty or contains non-integer key... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def filter_square_dict_values(dictionary: Dict[int, int]) -> Dict[int, int]:
"""
Filters and squares the values of a dictionary, considering only positive integer values.
Args:
dictionary (D... |
python_sharegpt_23k | 1,653 | Write a Python function called `multiply_lists` that takes in two lists of numbers and returns a new list of numbers in which each element is the product of the corresponding elements in the two input lists. The function should raise a `ValueError` if the two input lists do not have the same length. The function should... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def multiply_lists(list1: List[float], list2: List[float]) -> List[float]:
"""
Multiplies corresponding elements of two lists and returns a new list of products.
Args:
list1 (List[float]): T... |
python_sharegpt_23k | 1,661 | Write a Python function to remove all duplicates from a given list of numbers and sort the remaining elements in descending order. The function should have a time complexity of O(n log n) and should be implemented using only constant space (i.e., without using any additional data structures). Additionally, the function... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def remove_duplicates_and_sort(numbers: List[int]) -> List[int]:
"""
Removes all duplicates from the given list of numbers and sorts the remaining elements in descending order.
Args:
numbers... |
python_sharegpt_23k | 1,665 | Write a Python function to print the vowels in lowercase in reverse order and return the count of vowels printed. The function should not use any external libraries or modules. The code should start with:
```python
def print_vowels_and_count() -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def print_vowels_and_count() -> int:
"""
Prints the vowels in lowercase in reverse order and returns the count of vowels printed.
Returns:
int: The number of vowels printed.
"""
# Define the lowercase vowels... |
python_sharegpt_23k | 1,666 | Write a Python function to generate all permutations of a given list of letters without using any built-in library functions or external modules. The function should handle lists with duplicate elements and return the permutations in lexicographically sorted order. The function should:
1. Not use any extra space except... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_permutations(letters: List[str]) -> List[List[str]]:
"""
Generate all permutations of the given list of letters in lexicographically sorted order.
Args:
letters (List[str]): The... |
python_sharegpt_23k | 1,670 | Write a Python function to search for the first occurrence of a given number in a sorted array using a modified binary search algorithm. The function should return the index of the first occurrence of the number if it exists in the array, or -1 if it does not. The algorithm should have a time complexity of O(log n), wh... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_first_occurrence(arr: List[int], target: int) -> int:
"""
Searches for the first occurrence of a given number in a sorted array using a modified binary search algorithm.
Args:
arr (... |
python_sharegpt_23k | 1,672 | Write a Python function to implement a binary search algorithm that works on a rotated sorted array. The function should return the index of the number in the array if found, otherwise -1. The code should start with:
```python
from typing import List
def binary_search_rotated(data: List[int], search_num: int) -> int:
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def binary_search_rotated(data: List[int], search_num: int) -> int:
"""
Perform a binary search on a rotated sorted array to find the index of the search_num.
Args:
data (List[int]): The rot... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.