source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
python_sharegpt_23k | 6,189 | Write a Python function to find the index of the first occurrence of a given element in a list of integers. If the element is not present in the list, the function should return -1. The input list is guaranteed to have a length of at least 3. The function should only use basic array operations and not rely on any built... | Here is the Python code to solve the given problem in the markdown block:
```python
def find_first_occurrence(lst: list, element: int) -> int:
"""
Find the index of the first occurrence of a given element in a list of integers.
If the element is not present in the list, return -1.
Args:
lst (li... |
python_sharegpt_23k | 6,190 | Write a Python function to sort an array of numbers using only recursion. The function should implement the merge sort algorithm, which is a classic divide-and-conquer algorithm. The function should be able to handle arrays of any length, including empty arrays. The code should start with:
```python
from typing import ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def recursive_merge_sort(arr: List[int]) -> List[int]:
"""
Sorts an array of integers using the merge sort algorithm, implemented recursively.
Args:
arr (List[int]): The array of integers to... |
python_sharegpt_23k | 6,191 | Write a Python function that calculates the factorial of a given non-negative integer using type hinting to improve code readability and maintainability. The function should handle edge cases such as inputting a negative number or a non-integer value. The code should start with:
```python
from typing import Union
def ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Union
def factorial(n: Union[int, float]) -> Union[int, float]:
"""
Calculate the factorial of a given non-negative integer.
Args:
n (Union[int, float]): The non-negative integer for which to cal... |
python_sharegpt_23k | 6,197 | Write a Python function to search for a target integer in a list of integers and return the first index at which the target integer is found. If the target integer is not found in the list, the function should return -1. The function should be efficient and handle edge cases such as an empty list or a list where the ta... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def search_list(nums: List[int], target: int) -> int:
"""
Searches for the target integer in the given list and returns the first index at which the target is found.
If the target is not found, retur... |
python_sharegpt_23k | 6,198 | Write a Python function to count the number of unique words in a given sentence, excluding any common stopwords. The function should handle cases where the sentence contains punctuation marks and special characters. The function should be efficient and have a time complexity of O(n), where n is the length of the senten... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Set
import string
def count_unique_words(sentence: str, stopwords: Set[str]) -> int:
"""
Counts the number of unique words in a given sentence, excluding any common stopwords.
The function handles punctua... |
python_sharegpt_23k | 6,200 | Write a Python function to find and return the first `n` prime numbers within a specified range `[start, end]`. The function should use a helper function to determine if a number is prime. The code should start with:
```python
from typing import List
def find_n_primes_in_range(start: int, end: int, n: int) -> List[int... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def is_prime(n: int) -> bool:
"""
Check if a given number is prime.
Args:
n (int): The number to check for primality.
Returns:
bool: True if the number is prime, False otherwise... |
python_sharegpt_23k | 6,205 | Write a Python function to create a multi-dimensional array of size `rows` x `columns` where each element is initialized to the sum of its row and column indices. The function should handle the input validation to ensure that both `rows` and `columns` are positive integers.
The code should start with:
```python
from t... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def create_multi_dimensional_array(rows: int, columns: int) -> List[List[int]]:
"""
Creates a multi-dimensional array of size `rows` x `columns` where each element is initialized to the sum of its row an... |
python_sharegpt_23k | 6,208 | Write a Python function to calculate the average of numbers in a given list that are divisible by 3 and greater than 10. The function should handle cases where no such numbers exist by returning `None`.
The code should start with:
```python
from typing import List, Optional
def average_divisible_by_three_and_greater_... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def average_divisible_by_three_and_greater_than_ten(numbers: List[int]) -> Optional[float]:
"""
Calculate the average of numbers in the given list that are divisible by 3 and greater than 10.
... |
python_sharegpt_23k | 6,210 | Write a Python function to filter out all numbers divisible by both 3 and 4 from a given list of integers and then sort the remaining numbers in descending order. The function should start with:
```python
from typing import List
def filter_and_sort_divisibles(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_and_sort_divisibles(numbers: List[int]) -> List[int]:
"""
Filters out all numbers divisible by both 3 and 4 from the given list of integers and sorts the remaining numbers in descending order.... |
python_sharegpt_23k | 6,212 | Write a Python function that determines the eligibility for a specific activity based on age and prints a corresponding message. The function should take an integer `age` as input and use an `if-else` statement to check if the age is above or equal to a certain threshold (e.g., 18 for voting eligibility). If the age is... | Here is the Python code to solve the given problem in the markdown block:
```python
def check_eligibility(age: int) -> None:
"""
Determines the eligibility for a specific activity based on age and prints a corresponding message.
Args:
age (int): The age of the person to check eligibility for.
... |
python_sharegpt_23k | 6,213 | Write a Python function to partition a given list of numbers into three groups: odd numbers, even numbers, and prime numbers. The function should return a tuple containing three lists: one for odd numbers, one for even numbers, and one for prime numbers. The code should start with:
```python
from typing import List, Tu... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
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... |
python_sharegpt_23k | 6,214 | Write a Python function to find the maximum value in a given array of integers without using any built-in array functions or sorting algorithms. The function should iterate through the array and keep track of the maximum value encountered.
The code should start with:
```python
from typing import List
def find_max_val... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_max_value(array: List[int]) -> int:
"""
Find the maximum value in a given array of integers without using any built-in array functions or sorting algorithms.
Args:
array (List[int])... |
python_sharegpt_23k | 6,215 | Write a Python function to filter a list of strings, removing any words that include numbers and start with a capital letter. The function should return the filtered list of strings.
The code should start with:
```python
from typing import List
def filter_strings(list_of_strings: List[str]) -> List[str]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def filter_strings(list_of_strings: List[str]) -> List[str]:
"""
Filters a list of strings, removing any words that include numbers and start with a capital letter.
Args:
list_of_strings (Li... |
python_sharegpt_23k | 6,216 | Write a Python function to find all prime numbers within a given range [lower_limit, upper_limit]. The function should use the Sieve of Eratosthenes algorithm to efficiently determine the prime numbers.
The code should start with:
```python
from typing import List
def find_primes_in_range(lower_limit: int, upper_limi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_primes_in_range(lower_limit: int, upper_limit: int) -> List[int]:
"""
Find all prime numbers within the given range [lower_limit, upper_limit] using the Sieve of Eratosthenes algorithm.
Arg... |
python_sharegpt_23k | 6,218 | Write a Python function to generate an array of `n` random integers within a specified range, sort the array in ascending order, and then find the median value of the array. The function should handle both even and odd lengths of the array to compute the median correctly.
The code should start with:
```python
from typ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
def find_median_of_random_array(n: int, lower_bound: int, upper_bound: int) -> float:
"""
Generates an array of n random integers within the specified range, sorts the array, and finds the ... |
python_sharegpt_23k | 6,221 | Write a Python function to implement a linear search algorithm. The function should search for a target value within a given array of integers. If the target value is found, the function should return its index in the array. If the target value is not found, the function should return -1.
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 linear_search(array: List[int], target: int) -> int:
"""
Searches for a target value within a given array using a linear search algorithm.
Args:
array (List[int]): The array of integers ... |
python_sharegpt_23k | 6,223 | Write a Python function to generate and return the Fibonacci sequence up to the nth term. The function should take an integer `n` as input and return a list containing the Fibonacci sequence up to the nth term. If `n` is less than 1, the function should return an empty list.
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 fibonacci_sequence(n: int) -> List[int]:
"""
Generate and return the Fibonacci sequence up to the nth term.
Args:
n (int): The number of terms in the Fibonacci sequence to generate.
... |
python_sharegpt_23k | 6,224 | Write a Python function to generate a new list with its elements in reverse order without using any built-in functions or methods for list manipulation, such as `reverse()`. You can only use basic programming constructs like loops and conditional statements. The function should start with:
```python
from typing import ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def reverse_list(input_list: List[int]) -> List[int]:
"""
Generates a new list with its elements in reverse order without using built-in functions or methods.
Args:
input_list (List[int]): T... |
python_sharegpt_23k | 6,226 | Write a Python function to determine the winner of a game of Rock-Paper-Scissors-Lizard-Spock (RPSLS) using a dictionary to map outcomes instead of using if-else statements. The function should take two arguments, `player1` and `player2`, representing the shapes formed by each player (strings). The function should retu... | Here is the Python code to solve the given problem in the markdown block:
```python
def play_rpsls(player1: str, player2: str) -> str:
"""
Determine the winner of a game of Rock-Paper-Scissors-Lizard-Spock (RPSLS) using a dictionary to map outcomes.
Args:
player1 (str): The shape chosen by Player 1... |
python_sharegpt_23k | 6,227 | Write a Python function to calculate the product of a list of numbers, including handling negative integers and floating-point numbers. The function should return the product of all elements in the list. If the list is empty, the function should return 1.
The code should start with:
```python
from typing import List
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_product(numbers: List[float]) -> float:
"""
Calculate the product of all numbers in the given list.
Args:
numbers (List[float]): A list of numbers (integers or floats) to calcu... |
python_sharegpt_23k | 6,228 | Write a Python function to generate a unique random number within a specified range, ensuring that the generated number is not repeated within a given session. The function should be efficient and secure, leveraging the `random` module in Python. The code should start with:
```python
import random
from typing import Li... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
from typing import List
def generate_unique_random(start_range: int, end_range: int, generated_numbers: List[int]) -> int:
"""
Generates a unique random number within a specified range, ensuring that the number is... |
python_sharegpt_23k | 6,230 | Write a Python function to print the contents of a 2D array in a formatted manner. Each element should be printed on a new line, and all elements should be properly aligned to the left with a fixed width of 3 characters. The function should handle any size of 2D array.
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 print_2d_array(arr: List[List[int]]) -> None:
"""
Prints the contents of a 2D array in a formatted manner.
Each element is printed on a new line and left-aligned with a width of 3 characters.
... |
python_sharegpt_23k | 6,231 | Implement a Python function to sort a list of numbers 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 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 | 6,232 | Write a Python function to process a list of strings by converting all strings to lowercase, removing any duplicate strings, and sorting the remaining strings in alphabetical order. The function should return the processed list.
The code should start with:
```python
from typing import List
def process_strings(string_... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_strings(string_list: List[str]) -> List[str]:
"""
Processes a list of strings by converting all strings to lowercase,
removing any duplicate strings, and sorting the remaining strings
... |
python_sharegpt_23k | 6,234 | Write a Python function to compute the average value of all the elements in an array of size `n` (where `1 <= n <= 10^6`) of integers, where each integer is between `-10^9` and `10^9` inclusive. The function must compute the average value in `O(n)` time complexity and `O(1)` space complexity.
The code should start wit... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def compute_average(array: List[int]) -> float:
"""
Compute the average value of all the elements in an array of integers.
Args:
array (List[int]): The array of integers for which to compute... |
python_sharegpt_23k | 6,239 | Write a Python function to encrypt a given text using the Caesar Cipher algorithm. The function should handle both uppercase and lowercase letters, and it should not alter punctuation and spaces. The code should start with:
```python
def caesar_cipher_encrypt(text: str, key: int) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def caesar_cipher_encrypt(text: str, key: int) -> str:
"""
Encrypts the given text using the Caesar Cipher algorithm.
Args:
text (str): The plaintext to be encrypted.
key (int): The shift value for the Caesa... |
python_sharegpt_23k | 6,242 | Write a Python function to execute a given block of code a specified number of times and print the current iteration number within the block. The function should accept a callable (a function or lambda) and an integer representing the number of iterations. The function should execute the callable within a loop, passing... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Callable
def execute_block(func: Callable[[int], None], num_iterations: int) -> None:
"""
Executes a given block of code a specified number of times and prints the current iteration number within the block.
... |
python_sharegpt_23k | 6,251 | Write a Python function to find the most frequent value in a given list of integers. The list will always contain at least one repeated value. The function should return the value that appears most frequently.
The code should start with:
```python
from typing import List
def most_frequent_value(nums: List[int]) -> in... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
from collections import Counter
def most_frequent_value(nums: List[int]) -> int:
"""
Find the most frequent value in a given list of integers.
Args:
nums (List[int]): A list of integers with... |
python_sharegpt_23k | 6,252 | Write a Python function to convert an amount from one currency to another using a specific exchange rate provided by the user. The function should handle both positive and negative exchange rates and amounts. The code should start with:
```python
def convert_currency(amount: float, rate: float) -> float:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def convert_currency(amount: float, rate: float) -> float:
"""
Converts an amount from one currency to another using a specific exchange rate.
Args:
amount (float): The amount to be converted.
rate (float): ... |
python_sharegpt_23k | 6,253 | Write a Python function to process a list of strings by removing duplicates and counting the occurrences of each unique string. Additionally, the function should return the top 3 most occurring strings.
The code should start with:
```python
from typing import List, Dict, Tuple
def process_strings(strings: List[str]) ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Tuple
def process_strings(strings: List[str]) -> Tuple[List[str], Dict[str, int], List[str]]:
"""
Processes a list of strings by removing duplicates, counting occurrences of each unique string,
... |
python_sharegpt_23k | 6,254 | Write a Python function to find the maximum subarray sum in an array of integers, which may contain both positive and negative numbers. The array may also be empty. The function should return the maximum sum of any contiguous subarray within the given array.
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 max_subarray_sum(arr: List[int]) -> int:
"""
Find the maximum sum of any contiguous subarray in the given array.
Args:
arr (List[int]): The array of integers, which may contain both posi... |
python_sharegpt_23k | 6,260 | Write a Python function to find and return the items in a given list that appear only once. The list may contain integers, floats, strings, or a combination of these data types. The function should handle any input list size and provide the correct output. The code should start with:
```python
from typing import List, ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def get_unique_items(lst: List[Union[int, float, str]]) -> List[Union[int, float, str]]:
"""
Returns a list of items that appear only once in the given list.
Args:
lst (List[Union[int... |
python_sharegpt_23k | 6,266 | Write a Python function to format and print a string and an integer together to the console using different methods. The function should accept a string and an integer as input and print the formatted string using concatenation, string formatting, f-string, and the `sep` parameter of the `print` function.
The code sho... | Here is the Python code to solve the given problem in the markdown block:
```python
def print_string_and_integer(name: str, age: int) -> None:
"""
Prints a string and an integer together using different formatting methods.
Args:
name (str): The string to be printed.
age (int): The integer t... |
python_sharegpt_23k | 6,267 | Write a Python function to determine if a given number is a prime number efficiently, ensuring that the solution has a time complexity of O(sqrt(n)) and does not use any built-in libraries or functions for prime number generation or factorization. The function should handle edge cases such as negative numbers, 0, and 1... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_prime_efficient(n: int) -> bool:
"""
Determines if a given number is a prime number efficiently with a time complexity of O(sqrt(n)).
Args:
n (int): The number to check for primality.
Returns:
bo... |
python_sharegpt_23k | 6,273 | Write a Python function to generate a list of `n` unique random integers within a specified range `[min_val, max_val]`. The function should ensure that the generated list does not contain any duplicate numbers. The code should start with:
```python
from typing import List
import random
def generate_unique_random_numbe... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
def generate_unique_random_numbers(n: int, min_val: int, max_val: int) -> List[int]:
"""
Generates a list of `n` unique random integers within the specified range `[min_val, max_val]`.
... |
python_sharegpt_23k | 6,275 | Write a Python function to convert a list of integers into a single number and then reverse the digits of that number. The input list will always contain positive integers and will not be empty. The function should start with:
```python
from typing import List
def reverse_digits_of_list_to_number(array: List[int]) -> ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def reverse_digits_of_list_to_number(array: List[int]) -> int:
"""
Converts a list of integers into a single number and then reverses the digits of that number.
Args:
array (List[int]): A li... |
python_sharegpt_23k | 6,276 | Write a Python function to sort a given list in ascending order using the Bubble Sort algorithm without using any built-in sorting functions. The function should start with:
```python
from typing import List
def bubble_sort(lst: List[int]) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def bubble_sort(lst: List[int]) -> List[int]:
"""
Sorts the given list in ascending order using the Bubble Sort algorithm.
Args:
lst (List[int]): The list of integers to be sorted.
Retu... |
python_sharegpt_23k | 6,282 | Write a Python function to sort an array of objects by the value of a specified key in descending order. The key will always be a string containing a valid Python identifier. The array will always contain at least one object, and each object will always have the key specified. The function should be case-sensitive when... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def sort_array_by_key(arr: List[Dict[str, any]], key: str) -> List[Dict[str, any]]:
"""
Sorts an array of objects by the value of a specified key in descending order.
Args:
arr (List[D... |
python_sharegpt_23k | 6,284 | Write a Python function to determine if two given strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of another word or phrase. The function should be case-insensitive and should ignore any non-alphabetic characters such as spaces or punctuation marks. The function shou... | 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:
"""
Determine if two strings are anagrams of each other.
Args:
str1 (str): The first string to compare.
str2 (str): The second string to compare.
... |
python_sharegpt_23k | 6,289 | Write a Python function to process a 2D array by doubling each item and then squaring the doubled item. The function should return the modified 2D array.
The code should start with:
```python
from typing import List
def process_2d_array(arr: List[List[int]]) -> List[List[int]]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def process_2d_array(arr: List[List[int]]) -> List[List[int]]:
"""
Process a 2D array by doubling each item and then squaring the doubled item.
Args:
arr (List[List[int]]): The 2D array of i... |
python_sharegpt_23k | 6,290 | Write a Python function to randomly shuffle a list of integers such that the smallest value is always at the beginning of the shuffled list. The function should ensure that the rest of the list is shuffled randomly.
The code should start with:
```python
from typing import List
import random
def shuffle_with_smallest_... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
def shuffle_with_smallest_first(integers: List[int]) -> List[int]:
"""
Shuffles a list of integers such that the smallest value is always at the beginning of the shuffled list.
Args:
... |
python_sharegpt_23k | 6,291 | Write a Python function to find the biggest number in a given list of integers. The function should handle the case when the list is empty and return `None` in that case. If the list contains duplicate numbers, the function should return any one of the duplicate numbers if it is the biggest. The function should have a ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def find_biggest_number(my_list: List[int]) -> Optional[int]:
"""
Find the biggest number in a given list of integers.
Args:
my_list (List[int]): The list of integers from which to... |
python_sharegpt_23k | 6,295 | Write a Python function to filter elements from a given list based on a specified criteria. The criteria will be a lambda function that takes an element as input and returns a boolean value indicating whether the element should be included in the result. The function should return a new list containing only the element... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Callable
def filter_elements(lst: List[int], criteria: Callable[[int], bool]) -> List[int]:
"""
Filters elements from a given list based on a specified criteria.
Args:
lst (List[int]): The ... |
python_sharegpt_23k | 6,305 | Write a Python function to add two non-negative integers using only bitwise operators. The function should take two integers as input and return their sum. The code should start with:
```python
def add_numbers_bitwise(a: int, b: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def add_numbers_bitwise(a: int, b: int) -> int:
"""
Adds two non-negative integers using only bitwise operators.
Args:
a (int): The first non-negative integer.
b (int): The second non-negative integer.
... |
python_sharegpt_23k | 6,307 | Write a Python function to reverse a given list and return the reversed list. The function should use a for loop to iterate through the list in reverse order and construct the reversed list. The code should start with:
```python
from typing import List
def reverse_list(lst: List[int]) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def reverse_list(lst: List[int]) -> List[int]:
"""
Reverses the given list and returns the reversed list.
Args:
lst (List[int]): The list of integers to be reversed.
Returns:
Li... |
python_sharegpt_23k | 6,311 | Write a Python function to combine two sorted lists into a single sorted list. The elements in each list are unique and in ascending order. The function should handle lists of different lengths efficiently.
The code should start with:
```python
from typing import List
def combine_sorted_lists(list_1: List[int], list_... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def combine_sorted_lists(list_1: List[int], list_2: List[int]) -> List[int]:
"""
Combines two sorted lists into a single sorted list.
Args:
list_1 (List[int]): The first sorted list.
... |
python_sharegpt_23k | 6,312 | Write a Python function to compare two strings in a case-insensitive manner while ignoring leading and trailing white spaces. The function should return a boolean result indicating whether the two strings are equal after applying the mentioned transformations.
The code should start with:
```python
def compare_strings(... | Here is the Python code to solve the given problem in the markdown block:
```python
def compare_strings(string1: str, string2: str) -> bool:
"""
Compares two strings in a case-insensitive manner while ignoring leading and trailing white spaces.
Args:
string1 (str): The first string to compare.
... |
python_sharegpt_23k | 6,313 | Write a Python function to calculate the average of a list of numbers, ensuring that the list contains at least 5 elements. If the list has fewer than 5 elements, the function should return `None`.
The code should start with:
```python
from typing import List, Optional
def calculate_average(numbers: List[int]) -> Opt... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def calculate_average(numbers: List[int]) -> Optional[float]:
"""
Calculate the average of a list of numbers, ensuring the list contains at least 5 elements.
Args:
numbers (List[in... |
python_sharegpt_23k | 6,314 | Write a Python function to calculate the absolute difference between two integers within a specified range. The function should validate that both inputs are integers between 0 and 100, inclusive. If the inputs are invalid, the function should return `None` instead of raising an exception.
The code should start with:
... | Here is the Python code to solve the given problem in the markdown block:
```python
def absolute_difference_with_validation(num1: int, num2: int) -> int:
"""
Calculate the absolute difference between two integers within the range [0, 100].
Args:
num1 (int): The first integer.
num2 (int): Th... |
python_sharegpt_23k | 6,315 | Write a Python function to convert a string containing both integers and floating-point numbers to their respective number types. The string can also include scientific notation and negative numbers. The function should handle leading and trailing white spaces in the string and return the converted number. If the strin... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Union
def convert_to_number(string: str) -> Union[int, float, None]:
"""
Converts a string containing an integer or floating-point number to its respective number type.
The string can include scientific n... |
python_sharegpt_23k | 6,316 | Write a Python function to remove duplicates from a given list and return the list in ascending order. The function should handle lists of integers. The code should start with:
```python
from typing import List
def remove_duplicates_and_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 remove_duplicates_and_sort(arr: List[int]) -> List[int]:
"""
Removes duplicates from the given list and returns the list in ascending order.
Args:
arr (List[int]): The list of integers f... |
python_sharegpt_23k | 6,317 | Write a Python function to determine which elements of a given list are strings and return them in reverse order. You are not allowed to use any built-in methods or functions for reversing the list. The function should start with:
```python
from typing import List, Any
def reverse_strings_in_list(data: List[Any]) -> L... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Any
def reverse_strings_in_list(data: List[Any]) -> List[str]:
"""
Extracts strings from the given list and returns them in reverse order.
Args:
data (List[Any]): The list from which to ext... |
python_sharegpt_23k | 6,318 | Write a Python function to retrieve the location of the 3rd character in a given string without using any string manipulation functions or methods. The function should return the index of the 3rd character.
The code should start with:
```python
def get_third_character_index(s: str) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def get_third_character_index(s: str) -> int:
"""
Retrieve the index of the 3rd character in a given string without using any string manipulation functions or methods.
Args:
s (str): The input string.
Returns:
... |
python_sharegpt_23k | 6,319 | Write a Python function to calculate the average grade from a list of grades with a time complexity of O(1). The function should not use any built-in functions or libraries, and the grades will always be integers ranging from 0 to 100. The function should take the sum of the grades and the number of grades as inputs.
... | Here is the Python code to solve the given problem in the markdown block:
```python
def avg_grade(grades_sum: int, length: int) -> float:
"""
Calculate the average grade from the sum of grades and the number of grades.
Args:
grades_sum (int): The sum of all grades.
length (int): The number ... |
python_sharegpt_23k | 6,320 | Write a Python function to convert a given number of seconds into hours, minutes, and remaining seconds. The function should only accept positive integer values for the seconds parameter. If the input is invalid (non-positive or non-integer), the function should raise a `ValueError` with an appropriate message.
The co... | Here is the Python code to solve the given problem in the markdown block:
```python
def convert_time(seconds: int) -> str:
"""
Converts a given number of seconds into hours, minutes, and remaining seconds.
Args:
seconds (int): The number of seconds to convert. Must be a positive integer.
Retur... |
python_sharegpt_23k | 6,326 | Write a Python function to generate a list of unique random numbers between 0 and 1000. The function should ensure that each number in the list is unique and should handle the case where the number of requested elements exceeds 1000 by raising a `ValueError`. Additionally, if the number of requested elements is very cl... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
def generate_unique_random_numbers(num_elements: int) -> list:
"""
Generates a list of unique random numbers between 0 and 1000.
Args:
num_elements (int): The number of unique random numbers to genera... |
python_sharegpt_23k | 6,330 | Write a Python function to find the index of the maximum value in an array of positive integers. The array has a length of at least 10. The function should return the index of the maximum value.
The code should start with:
```python
from typing import List
def find_max_index(array: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_max_index(array: List[int]) -> int:
"""
Find the index of the maximum value in an array of positive integers.
Args:
array (List[int]): The array of positive integers with a length o... |
python_sharegpt_23k | 6,331 | Write a Python function to find the maximum element in a 2-dimensional array, which can contain both positive and negative numbers. The function should efficiently iterate through the array to determine the maximum value.
The code should start with:
```python
from typing import List
def find_max_element(arr: List[Lis... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_max_element(arr: List[List[int]]) -> int:
"""
Find the maximum element in a 2-dimensional array.
Args:
arr (List[List[int]]): A 2-dimensional array of integers.
Returns:
... |
python_sharegpt_23k | 6,334 | Write a Python function to iterate through a given 2-dimensional array and return a list of all elements in the order they appear. The function should handle any size of 2-dimensional array and should not print the elements but return them as a single list.
The code should start with:
```python
from typing import List... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def flatten_2d_array(array: List[List[any]]) -> List[any]:
"""
Flattens a 2-dimensional array into a single list of elements.
Args:
array (List[List[any]]): A 2-dimensional array (list of li... |
python_sharegpt_23k | 6,336 | Write a Python function to calculate the product of two integers without using the multiplication operator (`*`) or any built-in multiplication functions. The function should handle positive, negative, and zero inputs correctly. The code should start with:
```python
def multiply_without_operator(a: int, b: int) -> int:... | Here is the Python code to solve the given problem in the markdown block:
```python
def multiply_without_operator(a: int, b: int) -> int:
"""
Calculate the product of two integers without using the multiplication operator (*).
Args:
a (int): The first integer.
b (int): The second integer.
... |
python_sharegpt_23k | 6,340 | Write a Python function to determine if a given number is a prime number. The function should return `True` if the number is prime and `False` otherwise. The function should handle edge cases such as negative numbers, 0, and 1, which are not prime numbers. The code should start with:
```python
def is_prime(num: int) ->... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_prime(num: int) -> bool:
"""
Determine if a given number is a prime number.
Args:
num (int): The number to check for primality.
Returns:
bool: True if the number is prime, False otherwise.
""... |
python_sharegpt_23k | 6,341 | Write a Python function to calculate the size of a given array of integers in bytes. The function should take the array as input and return the total size in bytes. The size of each integer element is assumed to be 4 bytes.
The code should start with:
```python
from typing import List
def calculate_array_size(arr: Li... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_array_size(arr: List[int]) -> int:
"""
Calculate the total size of a given array of integers in bytes.
Args:
arr (List[int]): The array of integers for which to calculate the s... |
python_sharegpt_23k | 6,348 | Write a Python function to calculate the sum of all unique elements in a given list of integers. The function should have a time complexity of O(n), where n is the length of the input list. The input list can contain duplicates and can be empty. The list can contain both positive and negative integers.
The code should... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_of_unique_elements(lst: List[int]) -> int:
"""
Calculate the sum of all unique elements in a given list of integers.
Args:
lst (List[int]): The list of integers from which to calcula... |
python_sharegpt_23k | 6,351 | Write a Python function to check if a given string contains at least three consecutive special characters. Special characters are defined as any character that is not a word character (alphanumeric or underscore) or whitespace.
The code should start with:
```python
import re
def has_three_consecutive_special_chars(st... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def has_three_consecutive_special_chars(string: str) -> bool:
"""
Check if the given string contains at least three consecutive special characters.
Special characters are defined as any character that is not a wo... |
python_sharegpt_23k | 6,353 | Write a Python function to sort an array of strings in alphabetical order using the **insertion sort** algorithm. You are not allowed to use any built-in sorting functions or methods. The function should start with:
```python
from typing import List
def insertion_sort_strings(arr: List[str]) -> List[str]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def insertion_sort_strings(arr: List[str]) -> List[str]:
"""
Sorts an array of strings in alphabetical order using the insertion sort algorithm.
Args:
arr (List[str]): The array of strings t... |
python_sharegpt_23k | 6,354 | Write a Python function to remove all duplicate elements from a given list while maintaining the order of the original list. The function should have a time complexity of O(n) and a space complexity of O(n), where n is the number of elements in the list. The function should return a new list containing only the unique ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def remove_duplicates_from_list(lst: List[int]) -> List[int]:
"""
Removes all duplicate elements from the given list while maintaining the order of the original list.
Args:
lst (List[int]): ... |
python_sharegpt_23k | 6,355 | Write a Python function to implement a binary search algorithm that can efficiently find the position of a given target number in a sorted list of integers. The algorithm should have a time complexity of O(log n) and should not use any built-in search functions or libraries. The code should start with:
```python
from t... | 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 position of a target number in a sorted list of integers.
Args:
arr (List[int]): A... |
python_sharegpt_23k | 6,357 | Write a Python function to extract the first and last names from a given full name string and ensure that the first name starts with an uppercase letter and the last name starts with a lowercase letter. The function should handle cases where the full name contains only one name or more than two names. The code should s... | Here is the Python code to solve the given problem in the markdown block:
```python
def extract_names(full_name: str) -> tuple:
"""
Extracts the first and last names from a given full name string and ensures that the first name starts with an uppercase letter and the last name starts with a lowercase letter.
... |
python_sharegpt_23k | 6,361 | Write a Python function to compute the maximum value of a given list of integers without using the built-in `max()` function. The function should handle an empty list by returning `None`.
The code should start with:
```python
from typing import List, Optional
def find_max_value(lst: List[int]) -> Optional[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def find_max_value(lst: List[int]) -> Optional[int]:
"""
Compute the maximum value of a given list of integers without using the built-in max() function.
Args:
lst (List[int]): The... |
python_sharegpt_23k | 6,363 | Write a Python function to construct an array of N elements from a given string, where N is the length of the string. The function should return a list where each element is a character from the string. The time complexity should be O(N) and the space complexity should be O(N).
The code should start with:
```python
fr... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def create_array_from_string(string: str) -> List[str]:
"""
Constructs an array of N elements from a given string, where N is the length of the string.
Args:
string (str): The input string f... |
python_sharegpt_23k | 6,365 | Write a Python function to determine if a given number is present in a sorted list of integers using a binary search algorithm. The function should have a time complexity of O(log n), where n is the length of the list. The function should return `True` if the number is found in the list, and `False` otherwise.
The cod... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def is_number_in_list(lst: List[int], number: int) -> bool:
"""
Determines if a given number is present in a sorted list of integers using binary search.
Args:
lst (List[int]): A sorted list... |
python_sharegpt_23k | 6,368 | Write a Python function to determine if a given number is prime or not. The function must be implemented from scratch without using any built-in functions or libraries to check for prime numbers. The function should only use basic programming constructs such as loops and conditionals.
The code should start with:
```py... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_prime(num: int) -> bool:
"""
Determine if a given number is prime.
Args:
num (int): The number to check for primality.
Returns:
bool: True if the number is prime, False otherwise.
"""
# H... |
python_sharegpt_23k | 6,372 | Write a Python function to compute the product of two numbers, handling cases where one or both numbers are negative. The function should correctly determine the sign of the product based on the signs of the input numbers and return the absolute value of the product multiplied by the appropriate sign.
The code should ... | Here is the Python code to solve the given problem in the markdown block:
```python
def multiply_with_sign(num1: int, num2: int) -> int:
"""
Computes the product of two numbers, handling cases where one or both numbers are negative.
Args:
num1 (int): The first number.
num2 (int): The second... |
python_sharegpt_23k | 6,375 | Write a Python function to find the common elements between two given lists, ensuring that the output contains only unique elements even if the input lists contain duplicates. The function should handle large input lists efficiently, with a time complexity of O(n), where n is the total number of elements in the input l... | 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 the common elements between two lists, ensuring the output contains only unique elements.
Args:
list1 (Lis... |
python_sharegpt_23k | 6,376 | Write a Python function to access and return the value associated with a specified key in a nested dictionary structure. The dictionary can be nested within multiple levels of lists and dictionaries. The function should handle cases where the key might not exist at any level of nesting. If the key is not found, the fun... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Any, Union
def get_nested_value(data: Union[dict, list], key: str) -> Any:
"""
Recursively searches for and returns the value associated with the specified key in a nested dictionary or list structure.
A... |
python_sharegpt_23k | 6,378 | Write a Python function to preprocess a list of dictionaries representing people's information. Each dictionary should be modified to include new attributes based on the existing ones. Specifically, the function should add an "age_group" attribute based on the person's age and a "location" attribute based on the person... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def preprocess_data(data: List[Dict[str, any]]) -> List[Dict[str, any]]:
"""
Preprocesses a list of dictionaries representing people's information.
Each dictionary is modified to include an "a... |
python_sharegpt_23k | 6,380 | Write a Python function to create an array containing string representations of all odd numbers from 0 to a given integer `n`. The function should return the array. The code should start with:
```python
from typing import List
def create_odd_number_array(n: int) -> List[str]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def create_odd_number_array(n: int) -> List[str]:
"""
Creates an array containing string representations of all odd numbers from 0 to the given integer n.
Args:
n (int): The upper limit (inc... |
python_sharegpt_23k | 6,382 | Write a Python function to concatenate two arrays while ensuring that the resulting array does not contain any duplicate elements. The function should return the concatenated array sorted in ascending order.
The code should start with:
```python
from typing import List
def concatenate_arrays_without_duplicates(arr1: ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def concatenate_arrays_without_duplicates(arr1: List[int], arr2: List[int]) -> List[int]:
"""
Concatenates two arrays and returns a sorted list of unique elements.
Args:
arr1 (List[int]): Th... |
python_sharegpt_23k | 6,383 | Write a Python function to generate the first `n` prime numbers and return them as a list. The function should use a helper function to check if a number is prime. The code should start with:
```python
from typing import List
def generate_primes(n: int) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def is_prime(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 | 6,384 | Write a Python function to find the maximum value from a given array efficiently. The array can contain duplicate elements and can have a maximum length of 10^6. The time complexity of the solution should be O(n), where n is the length of the array.
The code should start with:
```python
from typing import List
def fi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_maximum(array: List[int]) -> int:
"""
Find the maximum value in a given array efficiently with a time complexity of O(n).
Args:
array (List[int]): The array from which to find the m... |
python_sharegpt_23k | 6,386 | Write a Python function to remove all vowels from a given sentence. The sentence may contain punctuation marks, special characters, and both uppercase and lowercase letters. The function should return the modified sentence with all vowels removed.
The code should start with:
```python
def remove_vowels(sentence: str) ... | Here is the Python code to solve the given problem in the markdown block:
```python
def remove_vowels(sentence: str) -> str:
"""
Removes all vowels from the given sentence and returns the modified sentence.
Args:
sentence (str): The input sentence from which vowels are to be removed.
Returns:
... |
python_sharegpt_23k | 6,392 | Write a Python function to reverse a given string using a while loop, without using any built-in string reversal functions or slicing. The function should take a string as input and return the reversed string.
The code should start with:
```python
def reverse_string(s: str) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def reverse_string(s: str) -> str:
"""
Reverses the given string using a while loop, without using any built-in string reversal functions or slicing.
Args:
s (str): The input string to be reversed.
Returns:
... |
python_sharegpt_23k | 6,393 | Write a Python function to fill a 2D array with zeros using a single loop and without using any built-in functions or methods. The function should take the number of rows and columns as input and return the filled 2D array. The code should start with:
```python
def fill_2d_array_with_zeros(rows: int, cols: int) -> list... | Here is the Python code to solve the given problem in the markdown block:
```python
def fill_2d_array_with_zeros(rows: int, cols: int) -> list:
"""
Fills a 2D array with zeros using a single loop and without using any built-in functions or methods.
Args:
rows (int): The number of rows in the 2D arr... |
python_sharegpt_23k | 6,395 | Write a Python function to sort an unsorted array of integers using the Quick Sort algorithm. The array will contain both positive and negative numbers. The output should be in ascending order. If there are duplicate numbers, they should be placed next to each other in the sorted array. Implement the Quick Sort algorit... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def quick_sort(arr: List[int]) -> List[int]:
"""
Sorts an unsorted array of integers using the Quick Sort algorithm.
Args:
arr (List[int]): The unsorted array of integers.
Returns:
... |
python_sharegpt_23k | 6,396 | Write a Python function to sort a list of user objects by their age in descending order, and then by their name in ascending order. Each user object is represented as a dictionary with keys 'name' and 'age'. The function should return the sorted list of user objects.
The code should start with:
```python
from typing i... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def sort_users_by_age_and_name(users: List[Dict[str, any]]) -> List[Dict[str, any]]:
"""
Sorts a list of user objects by their age in descending order, and then by their name in ascending order.
... |
python_sharegpt_23k | 6,399 | Write a Python function to simulate a fair coin toss and return the results. The function should take an optional parameter `num_tosses` which specifies the number of times the coin should be tossed. If `num_tosses` is not provided, the default value should be 10. The function should only accept positive integer values... | Here is the Python code to solve the given problem in the markdown block:
```python
import random
def simulate_coin_tosses(num_tosses: int = 10) -> tuple:
"""
Simulate a fair coin toss a specified number of times and return the counts of "Heads" and "Tails".
Args:
num_tosses (int, optional): The n... |
python_sharegpt_23k | 6,400 | Write a Python function to check if one string (`s2`) is a substring of another string (`s1`). The function should return `True` if `s2` is a substring of `s1`, and `False` otherwise. The function should handle strings with lengths up to \(10^5\) efficiently.
The code should start with:
```python
def is_substring(s1: ... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_substring(s1: str, s2: str) -> bool:
"""
Check if s2 is a substring of s1.
Args:
s1 (str): The main string in which to search for the substring.
s2 (str): The substring to search for in s1.
Retur... |
python_sharegpt_23k | 6,406 | Write a Python function to compare two dictionaries for equality, ensuring that the order of the key-value pairs does not affect the result. The function should return `True` if the dictionaries are equal (i.e., they contain the same key-value pairs), and `False` otherwise.
The code should start with:
```python
from t... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict
def are_dicts_equal(dict1: Dict, dict2: Dict) -> bool:
"""
Compare two dictionaries for equality, ignoring the order of key-value pairs.
Args:
dict1 (Dict): The first dictionary to compare.
... |
python_sharegpt_23k | 6,409 | Write a Python function to determine and return a list of numbers from 1 to 100 that are divisible by both 5 and 7. Additionally, the function should return a list of strings indicating whether each number is a multiple of 5, 7, or both.
The code should start with:
```python
from typing import List, Tuple
def find_di... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def find_divisible_numbers() -> Tuple[List[int], List[str]]:
"""
Finds numbers from 1 to 100 that are divisible by 5, 7, or both, and returns a list of these numbers
along with a corresponding... |
python_sharegpt_23k | 6,410 | Write a Python function to repeat a given string a specified number of times efficiently. The function should have a time complexity of O(n), where n is the length of the string, and a space complexity of O(1). The function should handle edge cases such as non-positive integers by returning an empty string.
The code s... | Here is the Python code to solve the given problem in the markdown block:
```python
def repeat_string_efficiently(string: str, integer: int) -> str:
"""
Repeats the given string the specified number of times efficiently.
Args:
string (str): The string to be repeated.
integer (int): The numb... |
python_sharegpt_23k | 6,413 | Write a Python function to delete an element at a given index from an array and shift all the elements after the deleted element to fill the gap. The function should handle invalid indices gracefully by returning a specific error message.
The code should start with:
```python
from typing import List, Union
def delete... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def delete_element_at_index(arr: List[int], index: int) -> Union[List[int], str]:
"""
Deletes an element at the specified index from the array and shifts all subsequent elements to fill the gap.
... |
python_sharegpt_23k | 6,415 | Write a Python function to implement a merge sort algorithm that sorts an array of integers in ascending order. The algorithm should have a time complexity of O(nlogn) and should not use any built-in sorting functions or libraries. The function should be able to handle arrays of any length, including empty arrays.
The... | 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 array of integers to be sorted.
... |
python_sharegpt_23k | 6,416 | Write a Python function to count the number of occurrences of a specified character in a given string. The function should handle the case where the input string is `None` by raising a `ValueError`. The code should start with:
```python
def count_character_occurrences(string: str, character: str) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def count_character_occurrences(string: str, character: str) -> int:
"""
Counts the number of occurrences of a specified character in a given string.
Args:
string (str): The input string in which to count the charac... |
python_sharegpt_23k | 6,418 | Write a Python function to compute the Levenshtein distance between two given words. The Levenshtein distance is defined as the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one word into the other. The function should start with:
```python
def levenshtein_distanc... | Here is the Python code to solve the given problem in the markdown block:
```python
def levenshtein_distance(word1: str, word2: str) -> int:
"""
Compute the Levenshtein distance between two words.
The Levenshtein distance is the minimum number of single-character edits
(insertions, deletions, or substi... |
python_sharegpt_23k | 6,423 | Write a Python function to calculate the nth Fibonacci number using an iterative approach with constant space complexity. The function should handle edge cases such as negative inputs and return `None` for invalid inputs. The code should start with:
```python
def fibonacci_iterative(n: int) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def fibonacci_iterative(n: int) -> int:
"""
Calculate the nth Fibonacci number using an iterative approach with constant space complexity.
Args:
n (int): The position in the Fibonacci sequence to calculate.
Ret... |
python_sharegpt_23k | 6,426 | Write a Python function to find the largest and smallest numbers in a given list of integers without using any built-in functions or libraries. The function should run in O(n) time complexity, where n is the size of the input list. The function should handle edge cases such as an empty list or a list with only one elem... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def find_largest_smallest(numbers: List[int]) -> Tuple[int, int]:
"""
Find the largest and smallest numbers in a given list of integers.
Args:
numbers (List[int]): The list of integer... |
python_sharegpt_23k | 6,430 | Write a Python function to calculate the squares of all elements in a given list `nums` without using any built-in functions or operators for exponentiation (such as `**` or `pow()`). The input list `nums` can contain both positive and negative integers. The function should return a new list `squared` that contains the... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_squared(nums: List[int]) -> List[int]:
"""
Calculate the squares of all elements in the given list 'nums' without using any built-in exponentiation functions or operators.
Args:
... |
python_sharegpt_23k | 6,431 | Write a Python function to calculate the sum of all numbers in a given list. The function should handle any list of integers, including empty lists. The code should start with:
```python
from typing import List
def find_number_sum(numbers: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_number_sum(numbers: List[int]) -> int:
"""
Calculate the sum of all numbers in a given list.
Args:
numbers (List[int]): A list of integers.
Returns:
int: The sum of all... |
python_sharegpt_23k | 6,435 | Write a Python function to calculate the sum of all elements in a given 2D array of integers that are greater than 10. The function should take a 2D list of integers as input and return the sum of all elements that meet the condition.
The code should start with:
```python
from typing import List
def sum_elements_grea... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_elements_greater_than_10(array: List[List[int]]) -> int:
"""
Calculate the sum of all elements in a 2D array that are greater than 10.
Args:
array (List[List[int]]): A 2D list of int... |
python_sharegpt_23k | 6,440 | Write a Python function to generate the Fibonacci sequence up to a specified number of elements. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. The function should return a list containing the Fibonacci sequence up to the specified number of ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_fibonacci(num_elements: int) -> List[int]:
"""
Generate the Fibonacci sequence up to a specified number of elements.
The Fibonacci sequence is a series of numbers where each number is t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.