source stringclasses 6
values | id int64 0 111k | instruction stringlengths 167 4.39k | response stringlengths 244 6.1k |
|---|---|---|---|
python_sharegpt_23k | 8,109 | Write a Python function to find the average of all elements in a given list of integers efficiently. The function must have a time complexity of O(n) and use only a constant amount of extra space. The code should start with:
```python
from typing import List
def find_average(nums: List[int]) -> float:
```
| Here is the Python code to solve the given problem in the markdown block:
:
```python
from typing import List
def find_average(nums: List[int]) -> float:
"""
Calculate the average of all elements in a given list of integers efficiently.
Args:
nums (List[int]): The list of integers from which to ca... |
python_sharegpt_23k | 8,110 | Write a Python function to sort a given array of integers using the Quick Sort algorithm, ensuring that the algorithm has a time complexity of O(nlogn) in all cases. The function should handle arrays with duplicate elements and should not use any additional data structures beyond the input array itself.
The code shoul... | 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 a given array of integers using the Quick Sort algorithm with a time complexity of O(nlogn) in all cases.
Args:
arr (List[int]): The ar... |
python_sharegpt_23k | 8,118 | Write a Python function to convert a list of strings into a set of tuples. Each tuple should contain a string from the original list, its length, and the number of vowels it contains. The function should handle both uppercase and lowercase vowels.
The code should start with:
```python
from typing import List, Set, Tup... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Set, Tuple
def convert_strings_to_tuples(strings: List[str]) -> Set[Tuple[str, int, int]]:
"""
Converts a list of strings into a set of tuples. Each tuple contains a string, its length, and the number o... |
python_sharegpt_23k | 8,119 | Write a Python function to validate if a given string is a US phone number in the format `(XXX) XXX-XXXX`, where `X` represents a digit from 0 to 9. The function should use regular expressions to perform the validation.
The code should start with:
```python
import re
def validate_us_phone_number(number: str) -> bool:... | Here is the Python code to solve the given problem in the markdown block:
```python
import re
def validate_us_phone_number(number: str) -> bool:
"""
Validates if the given string is a US phone number in the format (XXX) XXX-XXXX.
Args:
number (str): The phone number string to validate.
Return... |
python_sharegpt_23k | 8,121 | Write a Python function to find the second largest number and its frequency in a given array of integers. If there are multiple numbers with the same frequency, return the smallest number among them. The function should handle edge cases such as an empty array or an array with fewer than two distinct numbers.
The code... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional, Tuple
def find_second_largest_and_frequency(nums: List[int]) -> Optional[Tuple[int, int]]:
"""
Find the second largest number and its frequency in a given array of integers.
Args:
... |
python_sharegpt_23k | 8,126 | Write a Python function to check if a given number exists in a list of numbers and return a tuple containing a boolean indicating the presence of the number and the index of the number if it exists. If the number does not exist, the index should be `-1`.
The code should start with:
```python
from typing import List, T... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def check_number_in_list(numbers: List[int], target: int) -> Tuple[bool, int]:
"""
Check if a given number exists in a list of numbers and return a tuple containing a boolean indicating the presen... |
python_sharegpt_23k | 8,127 | Write a Python function to calculate the median of an array of numbers without using any built-in sorting functions or libraries. The input array will always contain an odd number of elements. The function should start with:
```python
from typing import List
def calculate_median_without_sorting(arr: List[int]) -> int:... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def calculate_median_without_sorting(arr: List[int]) -> int:
"""
Calculate the median of an array of numbers without using any built-in sorting functions.
Args:
arr (List[int]): The input ar... |
python_sharegpt_23k | 8,133 | Write a Python function to calculate the power of a number using only basic arithmetic operations (addition, subtraction, multiplication, and division) without using any built-in exponentiation functions or operators. The function should handle both positive and negative exponents.
The code should start with:
```pytho... | Here is the Python code to solve the given problem in the markdown block:
```python
def power(base: float, p: int) -> float:
"""
Calculate the power of a number using only basic arithmetic operations.
Args:
base (float): The base number.
p (int): The exponent.
Returns:
float: T... |
python_sharegpt_23k | 8,137 | Write a Python function to filter a given list of integers, returning a new list that includes only the prime numbers greater than 2. The function should use a list comprehension for the filtering process.
The code should start with:
```python
from typing import List
def filter_primes_greater_than_two(arr: 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 | 8,138 | Write a Python function to determine if a given string can be converted to a palindrome by considering only alphanumeric characters and ignoring the case. The function should return `True` if the string can be rearranged to form a palindrome, and `False` otherwise.
The code should start with:
```python
def can_be_pali... | Here is the Python code to solve the given problem in the markdown block:
```python
def can_be_palindrome(string: str) -> bool:
"""
Determines if a given string can be rearranged to form a palindrome.
Args:
string (str): The input string to check.
Returns:
bool: True if the string can ... |
python_sharegpt_23k | 8,143 | Write a Python function to find the most frequently occurring item in a list of integers, where the length of the list is `n` and each integer is in the range of 1 to `m`. The function should have a time complexity of O(n) and a space complexity of O(m).
The code should start with:
```python
from typing import List
d... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def most_frequent_item(arr: List[int], m: int) -> int:
"""
Find the most frequently occurring item in a list of integers.
Args:
arr (List[int]): The list of integers where each integer is in... |
python_sharegpt_23k | 8,146 | Write a Python function to calculate the sum of values in a given dataset while handling missing values and ensuring that only numeric values are summed. The dataset is a list of elements that can be integers, floats, or `None`. The function should ignore any non-numeric values and missing values (`None`).
The code sh... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Union
def sum_numeric_values(data: List[Union[int, float, None]]) -> Union[int, float]:
"""
Calculate the sum of numeric values in the given dataset, ignoring missing values and non-numeric types.
... |
python_sharegpt_23k | 8,147 | Write a Python function to implement a modified version of the selection sort algorithm that sorts a given array in descending order. The array may contain duplicate elements. The function should start with:
```python
from typing import List
def selection_sort_descending(arr: List[int]) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def selection_sort_descending(arr: List[int]) -> List[int]:
"""
Sorts the given array in descending order using a modified selection sort algorithm.
Args:
arr (List[int]): The array to be so... |
python_sharegpt_23k | 8,148 | Write a Python function to generate two lists: one containing 10 random numbers within the range of 1 to 100 (inclusive), and the other containing 10 random prime numbers within the same range. The function should return a tuple containing these two lists.
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, Tuple
import random
def is_prime(n: int) -> bool:
"""
Check if a number is prime.
Args:
n (int): The number to check.
Returns:
bool: True if the number is prime, False otherwis... |
python_sharegpt_23k | 8,153 | Write a Python function to convert a given string into a list of characters, where each character is represented as a string. The function should handle strings of any length, including empty strings. The code should start with:
```python
from typing import List
def string_to_character_list(s: str) -> List[str]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def string_to_character_list(s: str) -> List[str]:
"""
Converts a given string into a list of characters, where each character is represented as a string.
Args:
s (str): The input string to ... |
python_sharegpt_23k | 8,156 | Write a Python function to count the occurrences of each letter in a given string, disregarding case sensitivity and excluding any non-alphabetic characters. The function should return a dictionary where the keys are the letters and the values are their respective counts.
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 Dict
def count_letter_occurrences(input_string: str) -> Dict[str, int]:
"""
Counts the occurrences of each letter in a given string, disregarding case sensitivity and excluding non-alphabetic characters.
... |
python_sharegpt_23k | 8,158 | Write a Python function to count the number of valid jokes that can be formed from a given input string based on specific rules. A valid joke must meet the following criteria:
1. The string must contain at least one vowel (a, e, i, o, u).
2. The string must contain at least one consonant (any letter that is not a vowel... | Here is the Python code to solve the given problem in the markdown block:
```python
def count_valid_jokes(input_string: str) -> int:
"""
Count the number of valid jokes that can be formed from the given input string.
A valid joke must meet the following criteria:
1. The string must contain at least one... |
python_sharegpt_23k | 8,159 | Write a Python function to create a deep copy of a nested list and demonstrate the difference between a shallow copy and a deep copy. The function should take a nested list as input and return a deep copy of the list. Additionally, provide a code snippet to show the difference between a shallow copy and a deep copy by ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import copy
def deep_copy_nested_list(nested_list: List[List[int]]) -> List[List[int]]:
"""
Creates a deep copy of a nested list.
Args:
nested_list (List[List[int]]): The nested list to be d... |
python_sharegpt_23k | 8,161 | Write a Python function to create an employee dictionary, print employee details as a formatted string, and sort a list of employees by their age using a stable sorting algorithm. The functions should be implemented using pure functions and higher-order functions. The `print_details` function should return a string ins... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict, Callable
def create_employee(name: str, age: int) -> Dict[str, str]:
"""
Create an employee dictionary with the given name and age.
Args:
name (str): The name of the employee.
... |
python_sharegpt_23k | 8,162 | Write a Python function to flatten a list of lists into a single list without using any built-in functions or methods that directly flatten a list. The function should handle lists of any depth, meaning it should recursively flatten nested lists.
The code should start with:
```python
from typing import List
def flatt... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def flatten_list(lst: List) -> List:
"""
Flattens a list of lists into a single list.
Args:
lst (List): The list of lists to be flattened.
Returns:
List: A single list containin... |
python_sharegpt_23k | 8,165 | Write a Python function to filter out and return a list of prime numbers from a given list of integers. The function should efficiently determine if a number is prime and include it in the result list if it is.
The code should start with:
```python
from typing import List
def get_prime_numbers(numbers: List[int]) -> ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import math
def get_prime_numbers(numbers: List[int]) -> List[int]:
"""
Returns a list of prime numbers from the given list of integers.
Args:
numbers (List[int]): The list of integers to fi... |
python_sharegpt_23k | 8,167 | Write a Python function to check if all elements in a given list are unique and are in strictly ascending order. The function should have a time complexity less than O(n^2). The code should start with:
```python
from typing import List
def is_unique_and_ascending(lst: List[int]) -> bool:
```
| Here is the Python code to solve the given problem in the markdown block:
:
```python
from typing import List
def is_unique_and_ascending(lst: List[int]) -> bool:
"""
Check if all elements in the given list are unique and in strictly ascending order.
Args:
lst (List[int]): The list of integers to ... |
python_sharegpt_23k | 8,170 | Write a Python function to generate a list of `n` random numbers within a specified range `[min_value, max_value]`. The function should ensure that the generated numbers are unique and sorted in ascending order. The code should start with:
```python
from typing import List
import random
def generate_unique_sorted_rand... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
def generate_unique_sorted_random_numbers(n: int, min_value: int, max_value: int) -> List[int]:
"""
Generates a list of `n` unique random numbers within the range `[min_value, max_value]` a... |
python_sharegpt_23k | 8,171 | Write a Python function to parse a text string given a simple regular expression and return the matches. The regular expression can include the following elements:
- Literal characters (e.g., `a`, `b`, `c`)
- The dot character `.` which matches any single character
- The asterisk `*` which matches zero or more occurren... | Here is the Python code to solve the given problem in the markdown block:
```python
def match_regex(regex: str, text: str) -> bool:
"""
Matches a text string against a simple regular expression.
Args:
regex (str): The regular expression to match against.
text (str): The text string to be ma... |
python_sharegpt_23k | 8,173 | Write a Python function to determine if a given positive integer greater than 1 is a prime number. The function should also check if the input is within the range of 2 to 10^9, inclusive. If the input is out of this range, the function should return `False`.
The code should start with:
```python
def is_prime_number(nu... | Here is the Python code to solve the given problem in the markdown block:
```python
def is_prime_number(num: int) -> bool:
"""
Determines if a given positive integer greater than 1 is a prime number.
Also checks if the input is within the range of 2 to 10^9, inclusive.
Args:
num (int): The posi... |
python_sharegpt_23k | 8,174 | Write a Python function to reverse a given string in-place using a loop, ensuring a time complexity of O(n) and a space complexity of O(1), where n is the length of the input string. The function should not create any new strings or data structures, and it should not use recursion.
The code should start with:
```pytho... | Here is the Python code to solve the given problem in the markdown block:
```python
def reverse_string_in_place(s: str) -> str:
"""
Reverses the given string in-place using a loop with O(n) time complexity and O(1) space complexity.
Args:
s (str): The input string to be reversed.
Returns:
... |
python_sharegpt_23k | 8,176 | Write a Python function to calculate the average of the sums of numbers across all non-empty arrays within a given array of arrays. Each array within the main array can have a different length, and empty arrays should be ignored when calculating the sum and average.
The code should start with:
```python
from typing im... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def average_of_sums(arr: List[List[int]]) -> float:
"""
Calculate the average of the sums of numbers across all non-empty arrays within a given array of arrays.
Args:
arr (List[List[int]]): ... |
python_sharegpt_23k | 8,178 | Write a Python function to count the total number of even numbers in a given array and compute the sum of all even numbers. The function should efficiently handle arrays with a size of up to \(10^6\) elements. The code should start with:
```python
from typing import List, Tuple
def count_and_sum_even_numbers(arr: List... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def count_and_sum_even_numbers(arr: List[int]) -> Tuple[int, int]:
"""
Counts the total number of even numbers in the given array and computes the sum of all even numbers.
Args:
arr (... |
python_sharegpt_23k | 8,179 | Write a Python function to generate a new array based on the given rules from a previous array. The new array should have four elements:
1. The first element is the sum of the first and second elements of the previous array.
2. The second element is the difference between the first and second elements of the previous a... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_new_array(previous_array: List[int]) -> List[float]:
"""
Generates a new array based on the given rules from a previous array.
Args:
previous_array (List[int]): A list containin... |
python_sharegpt_23k | 8,180 | Write a Python function to find the largest number in a given list of integers without using any built-in sorting or max functions. The function should iterate through the list and keep track of the largest number encountered so far. The code should start with:
```python
from typing import List
def find_largest_number... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_largest_number(arr: List[int]) -> int:
"""
Find the largest number in a given list of integers without using any built-in sorting or max functions.
Args:
arr (List[int]): The list o... |
python_sharegpt_23k | 8,181 | Write a Python function to create a dictionary from a given list of keys, where each key maps to a list of integers. The length of each list should be determined by the index of the key in the given list. Specifically, the list for the key at index `i` should contain integers from `0` to `i` (inclusive).
The code shou... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def create_dictionary_from_list(lst: List[str]) -> Dict[str, List[int]]:
"""
Creates a dictionary from a given list of keys, where each key maps to a list of integers.
The length of each list i... |
python_sharegpt_23k | 8,183 | Write a Python function to add two lists of numbers element-wise, where each list can have varying lengths. If one list is shorter than the other, the missing elements should be considered as 0. The function should return a new list containing the element-wise sums.
The code should start with:
```python
from typing im... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
from itertools import zip_longest
def add_lists_elementwise(list1: List[int], list2: List[int]) -> List[int]:
"""
Adds two lists of numbers element-wise, where each list can have varying lengths.
If ... |
python_sharegpt_23k | 8,186 | Write a Python function to find the position of a target number in a sorted array using an iterative binary search algorithm. The function should have a time complexity of O(log n), where n is the length of the array. If the target number is not found in the array, the function should return -1.
The code should start ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_position_in_array(arr: List[int], target: int) -> int:
"""
Find the position of a target number in a sorted array using an iterative binary search algorithm.
Args:
arr (List[int]): ... |
python_sharegpt_23k | 8,190 | Write a Python function to sort a list of integers in increasing order using the Merge Sort algorithm. The function should not use any built-in sorting functions or methods. Additionally, the function should have a time complexity of O(nlogn) and should not use any additional data structures. The input list can contain... | 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 increasing order using the Merge Sort algorithm.
Args:
arr (List[int]): The list of integers to be sorted.
R... |
python_sharegpt_23k | 8,192 | Write a Python function to determine the sum of all the even numbers in a given list of integers. The function should iterate through the list, check if each number is even, and if so, add it to a running total. The function should return the total sum of all even numbers.
The code should start with:
```python
from ty... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_of_even_numbers(numbers: List[int]) -> int:
"""
Calculate the sum of all even numbers in the given list.
Args:
numbers (List[int]): A list of integers.
Returns:
int: The... |
python_sharegpt_23k | 8,196 | Write a Python function to select all prime numbers from a given array of integers. The function should return a list of prime numbers. The code should start with:
```python
from typing import List
def select_prime_numbers(array: 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:
"""
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 | 8,197 | Write a Python function to sort a given list of integers in descending order using a custom sorting algorithm. The function should implement a modified version of the bubble sort algorithm to achieve this. The code should start with:
```python
from typing import List
def sort_descending(arr: List[int]) -> List[int]:
`... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sort_descending(arr: List[int]) -> List[int]:
"""
Sorts the given list of integers in descending order using a modified bubble sort algorithm.
Args:
arr (List[int]): The list of integers... |
python_sharegpt_23k | 8,198 | Write a Python function to generate and print the Fibonacci sequence up to the nth number, where n is a prime number. The function should take an integer `n` as input and print the Fibonacci sequence if `n` is a prime number. If `n` is not a prime number, the function should print a message indicating that `n` is not a... | Here is the Python code to solve the given problem in the markdown block:
```python
def print_fibonacci_up_to_prime(n: int) -> None:
"""
Prints the Fibonacci sequence up to the nth number if n is a prime number.
If n is not a prime number, prints a message indicating that n is not a prime number.
Args:... |
python_sharegpt_23k | 8,199 | Write a Python function to extract the last element from a given list without using any built-in Python functions or methods that directly extract the last element. The function should iterate through the list to find the last element.
The code should start with:
```python
from typing import List, Any
def extract_las... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Any
def extract_last_element(lst: List[Any]) -> Any:
"""
Extracts the last element from a given list without using built-in functions or methods that directly access the last element.
Args:
... |
python_sharegpt_23k | 8,200 | Write a Python function to convert each word in a given string to uppercase. The function should handle multiple spaces between words and leading/trailing spaces. The code should start with:
```python
def convert_to_uppercase(string: str) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def convert_to_uppercase(string: str) -> str:
"""
Converts each word in the given string to uppercase.
Args:
string (str): The input string containing words to be converted to uppercase.
Returns:
str: A... |
python_sharegpt_23k | 8,202 | Write a Python function to generate the Fibonacci sequence up to the nth element. The function should return a list containing the first n elements of the Fibonacci sequence. The code should start with:
```python
from typing import List
def generate_fibonacci(n: int) -> List[int]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_fibonacci(n: int) -> List[int]:
"""
Generate the Fibonacci sequence up to the nth element.
Args:
n (int): The number of elements in the Fibonacci sequence to generate.
Retu... |
python_sharegpt_23k | 8,204 | Write a Python function to check if a given string contains any special characters. The function should return `True` if the string contains at least one special character and `False` otherwise. The special characters to check for are defined in a string `special_characters`.
The code should start with:
```python
def ... | Here is the Python code to solve the given problem in the markdown block:
```python
def contains_special_characters(string: str) -> bool:
"""
Checks if the given string contains any special characters.
Args:
string (str): The input string to be checked for special characters.
Returns:
... |
python_sharegpt_23k | 8,210 | Write a Python function to determine if any two distinct numbers from a given list sum up to a given target sum. The function should run in O(n) time complexity and O(n) space complexity, where n is the length of the list. You cannot use any built-in sorting or searching functions.
The code should start with:
```pytho... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def is_sum_present(numbers: List[int], target_sum: int) -> bool:
"""
Determines if any two distinct numbers from the given list sum up to the target sum.
Args:
numbers (List[int]): The list ... |
python_sharegpt_23k | 8,211 | Write a Python function to format a given date string in the format "Day-Name, Month Name, Day, Year". The input date string is in the format "DD-MM-YYYY". The function should convert the input date string to a `datetime` object, extract the day name and month name, and then format the date according to the specified f... | Here is the Python code to solve the given problem in the markdown block:
```python
from datetime import datetime
def format_date(date_str: str) -> str:
"""
Formats a given date string in the format "DD-MM-YYYY" to "Day-Name, Month Name, Day, Year".
Args:
date_str (str): The input date string in t... |
python_sharegpt_23k | 8,212 | Write a Python function to calculate the base-2 logarithm of a given positive integer. The function should return the logarithm as an integer, which represents the exponent to which 2 must be raised to produce the input number.
The code should start with:
```python
import math
def calculate_base_2_logarithm(n: int) -... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def calculate_base_2_logarithm(n: int) -> int:
"""
Calculate the base-2 logarithm of a given positive integer.
Args:
n (int): The positive integer for which to calculate the base-2 logarithm.
Retur... |
python_sharegpt_23k | 8,213 | Write a Python function to count the number of distinct words in a given string of text, considering case insensitivity and ignoring common stop words. The function should handle words separated by spaces, punctuation marks, or special characters. The code should start with:
```python
from typing import List
import re
... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def count_distinct_words_with_stop_words(text: str, stop_words: List[str]) -> int:
"""
Count the number of distinct words in a given string of text, considering case insensitivity and ignoring ... |
python_sharegpt_23k | 8,215 | Write a Python function to generate a list of all days of the week in reverse order. The function should return the list of days in reverse order without printing them. The code should start with:
```python
from typing import List
def reverse_days_of_week() -> List[str]:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def reverse_days_of_week() -> List[str]:
"""
Generate a list of all days of the week in reverse order.
Returns:
List[str]: A list containing the days of the week in reverse order.
"""
... |
python_sharegpt_23k | 8,216 | Write a Python function to create a new array that is a copy of the given input array, consisting of all elements smaller than 5. Additionally, the new array should only contain odd numbers and the length of the new array should not exceed 5. If there are no odd numbers smaller than 5, the new array should be empty.
T... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def create_new_array(input_array: List[int]) -> List[int]:
"""
Create a new array consisting of all elements smaller than 5 from the input array.
The new array should only contain odd numbers and its... |
python_sharegpt_23k | 8,217 | Write a Python function to convert a given positive integer to its string representation in a specified base between 2 and 16 (inclusive). The function should be recursive and should return the result as a string. The code should start with:
```python
def convert_number_to_base_string(number: int, base: int) -> str:
``... | Here is the Python code to solve the given problem in the markdown block:
```python
def convert_number_to_base_string(number: int, base: int) -> str:
"""
Convert a given positive integer to its string representation in a specified base between 2 and 16 (inclusive).
Args:
number (int): The positive ... |
python_sharegpt_23k | 8,219 | Write a Python function to combine two input strings into a full name, ensuring that any leading or trailing white spaces are removed, the first letter of each name is capitalized, and all other letters are in lowercase. The combined full name should have a space between the first name and the last name. The function s... | Here is the Python code to solve the given problem in the markdown block:
```python
def combine_name(first_name: str, last_name: str) -> str:
"""
Combines two input strings into a full name, ensuring that any leading or trailing white spaces are removed,
the first letter of each name is capitalized, and all... |
python_sharegpt_23k | 8,220 | Write a Python function to flatten a nested dictionary. The function should take a dictionary as input and return a flattened dictionary where any nested dictionaries are flattened into a single level dictionary. The keys of the output dictionary should be in the format "parentkey_childkey" for nested keys. The functio... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Dict, Any
def flatten_nested_dict(dictionary: Dict[str, Any], parent_key: str = '', sep: str = '_') -> Dict[str, Any]:
"""
Flatten a nested dictionary into a single-level dictionary.
Args:
dictio... |
python_sharegpt_23k | 8,222 | Write a Python function to expand each element in a list of strings into a set of characters. Each element in the list should be expanded into a set of characters only if the string contains at least one vowel. The resulting sets of characters should be sorted in descending order based on the number of vowels in each s... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Set
def expand_strings(strings: List[str]) -> List[Set[str]]:
"""
Expands each string in the input list into a set of characters if the string contains at least one vowel.
The resulting sets are sor... |
python_sharegpt_23k | 8,224 | Write a Python function to identify if there is any duplicate element in a given list without using additional data structures such as sets or dictionaries. The function should return `True` if there is at least one duplicate element, otherwise `False`. 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 has_duplicate(lst: List[int]) -> bool:
"""
Determines if there is any duplicate element in the given list without using additional data structures.
Args:
lst (List[int]): The list of int... |
python_sharegpt_23k | 8,226 | Write a Python function to remove duplicate words from a given sentence and count the number of unique words. The function should convert all words to lowercase before removing duplicates. The code should start with:
```python
from typing import Tuple
def remove_duplicates_and_count_unique(sentence: str) -> Tuple[set,... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import Tuple
import re
def remove_duplicates_and_count_unique(sentence: str) -> Tuple[set, int]:
"""
Removes duplicate words from the given sentence and counts the number of unique words.
All words are converted... |
python_sharegpt_23k | 8,233 | Write a Python function to reverse the order of elements in a given list using only one temporary variable for swapping. The function should start with:
```python
from typing import List
def reverse_list_with_one_temp(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_with_one_temp(lst: List[int]) -> List[int]:
"""
Reverses the order of elements in a given list using only one temporary variable for swapping.
Args:
lst (List[int]): The l... |
python_sharegpt_23k | 8,237 | Write a Python function to randomly sample a list without replacement. The function should take a list of integers as input and return a new list containing the same elements in a random order. The function should ensure that each element from the original list appears exactly once in the sampled list.
The code should... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
def sample_list_without_replacement(original_list: List[int]) -> List[int]:
"""
Randomly samples the elements of a list without replacement.
Args:
original_list (List[int]): Th... |
python_sharegpt_23k | 8,238 | Write a Python function to print the square of all odd numbers within a given range. The function should take two integers, `start` and `end`, as input and print the square of each odd number between `start` (inclusive) and `end` (exclusive).
The code should start with:
```python
def print_odd_squares(start: int, end:... | Here is the Python code to solve the given problem in the markdown block:
```python
def print_odd_squares(start: int, end: int) -> None:
"""
Prints the square of each odd number within the given range [start, end).
Args:
start (int): The starting integer (inclusive) of the range.
end (int):... |
python_sharegpt_23k | 8,239 | Write a Python function to remove duplicates from a given list and return a new list with the remaining elements sorted 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 a new list with the remaining elements sorted in ascending order.
Args:
ar... |
python_sharegpt_23k | 8,240 | Write a Python function to convert a list of floating-point numbers into a list of strings with a specified number of decimal places. The function should handle an arbitrary number of variables and ensure that all numbers are formatted to the same number of decimal places.
The code should start with:
```python
from ty... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def format_numbers(numbers: List[float], decimal_places: int) -> List[str]:
"""
Converts a list of floating-point numbers into a list of strings with a specified number of decimal places.
Args:
... |
python_sharegpt_23k | 8,242 | Write a Python function to evaluate a given NumPy array and return the maximum absolute difference between any two elements in the array. The difference is calculated by subtracting the smaller element from the larger element. The code should start with:
```python
import numpy as np
def max_abs_difference(arr: np.ndar... | Here is the Python code to solve the given problem in the markdown block:
```python
import numpy as np
def max_abs_difference(arr: np.ndarray) -> float:
"""
Calculate the maximum absolute difference between any two elements in a given NumPy array.
Args:
arr (np.ndarray): The input NumPy array.
... |
python_sharegpt_23k | 8,245 | Write a Python function to perform a binary search in a sorted array of strings with up to 1 million elements. The array may contain duplicate strings, and the search should return the index of the first occurrence of the target string. If the target string is not found, the function should return -1.
The code should ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def binary_search_first_occurrence(arr: List[str], target: str) -> int:
"""
Perform a binary search to find the index of the first occurrence of the target string in a sorted array of strings.
Args:... |
python_sharegpt_23k | 8,248 | Write a Python function that processes a list of items and stops processing when a specific condition is met. The function should return the list of items processed before the condition was met. The code should start with:
```python
from typing import List, Any
def process_until_condition(items: List[Any], condition_f... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Any
def process_until_condition(items: List[Any], condition_func: callable) -> List[Any]:
"""
Processes a list of items and stops processing when a specific condition is met.
Args:
items (L... |
python_sharegpt_23k | 8,252 | Write a Python function to iterate over the items in a given dictionary and return a list of formatted strings, where each string represents a key-value pair from the dictionary. The format of each string should be "key: value". The function should start with:
```python
from typing import Dict, List
def format_dict_it... | Here is the Python code to solve the given problem in the markdown block:
:
```python
from typing import Dict, List
def format_dict_items(my_dict: Dict[str, int]) -> List[str]:
"""
Iterates over the items in the given dictionary and returns a list of formatted strings,
where each string represents a key-va... |
python_sharegpt_23k | 8,253 | Write a Python function to combine two lists of strings without duplication and in alphabetical order. The function should take two lists as input and return a single list containing all unique elements from both lists, sorted in alphabetical order.
The code should start with:
```python
from typing import List
def co... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def combine_lists_alphabetically(list_one: List[str], list_two: List[str]) -> List[str]:
"""
Combines two lists of strings without duplication and returns a single list sorted in alphabetical order.
... |
python_sharegpt_23k | 8,254 | Write a Python function to create a new list containing the square of each element in the given list, but exclude any numbers that are divisible by 3. The function should start with:
```python
from typing import List
def square_and_exclude_divisible_by_3(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 square_and_exclude_divisible_by_3(arr: List[int]) -> List[int]:
"""
Create a new list containing the square of each element in the given list,
but exclude any numbers that are divisible by 3.
... |
python_sharegpt_23k | 8,258 | Write a Python function to find and print the names and populations of the three most populous countries from a given list of countries, each represented as a dictionary with keys 'name' and 'population'. Additionally, the function should print the average population of these top three countries and the name and popula... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Dict
def analyze_countries(countries: List[Dict[str, int]]) -> None:
"""
Analyzes the given list of countries to find and print the names and populations of the three most populous countries,
the av... |
python_sharegpt_23k | 8,265 | Write a Python function to find the index of the first occurrence of an element in a given array, but only if the element occurs consecutively at least two times in a row. If there are no consecutive occurrences, return -1. The function should start with:
```python
from typing import List
def find_first_consecutive_oc... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def find_first_consecutive_occurrence(arr: List[int]) -> int:
"""
Find the index of the first occurrence of an element in the given array, but only if the element occurs consecutively at least two times ... |
python_sharegpt_23k | 8,269 | Write a Python function to remove all occurrences of a specified value from a given list and return the updated list along with the count of removed elements. The function should handle lists of integers and the value to be removed can be any integer. 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_elements(array: List[int], value: int) -> Tuple[List[int], int]:
"""
Removes all occurrences of a specified value from a given list and returns the updated list along with the count of ... |
python_sharegpt_23k | 8,271 | Write a Python function to get the second-to-last element from a given list efficiently. The list may contain up to \(10^6\) elements. The function should handle cases where the list has fewer than two elements by returning `None`.
The code should start with:
```python
from typing import List, Optional
def get_second... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def get_second_to_last_element(my_list: List[int]) -> Optional[int]:
"""
Returns the second-to-last element from the given list.
Args:
my_list (List[int]): The list from which to e... |
python_sharegpt_23k | 8,273 | Write a Python function that takes an integer as input and returns a tuple containing two elements: a list of the digits of the number and a boolean indicating whether the number is a prime number. The function should handle both positive and negative integers.
The code should start with:
```python
def analyze_number(... | Here is the Python code to solve the given problem in the markdown block:
```python
def analyze_number(number: int) -> tuple:
"""
Analyzes the given number by breaking it down into its digits and checking if it is a prime number.
Args:
number (int): The number to be analyzed.
Returns:
... |
python_sharegpt_23k | 8,276 | Write a Python function to extract all words ending with 'sion' from a given paragraph of text. The words should be preceded by a space or a punctuation mark and followed by a space or a punctuation mark. The paragraph may contain up to 500 words and should be case-insensitive. The extracted words should be sorted in a... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import re
def extract_sion_words(paragraph: str) -> List[str]:
"""
Extracts all words ending with 'sion' from a given paragraph of text.
The words should be preceded by a space or a punctuation mark ... |
python_sharegpt_23k | 8,280 | Write a Python function to calculate the average age, maximum age, and minimum age of a group of people from a given list of lists. Each sublist contains a person's name and age. The function should return a tuple containing the average age, maximum age, and minimum age.
The code should start with:
```python
from typi... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def calculate_age_stats(people: List[List[str]]) -> Tuple[float, int, int]:
"""
Calculate the average age, maximum age, and minimum age of a group of people.
Args:
people (List[List[s... |
python_sharegpt_23k | 8,283 | Write a Python function to calculate the sum of the product of the elements of each sublist in a nested list. Each sublist contains integers, and the function should return the sum of the products of the elements in each sublist.
The code should start with:
```python
from typing import List
def sum_of_products(nested... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_of_products(nested_list: List[List[int]]) -> int:
"""
Calculate the sum of the product of the elements of each sublist in a nested list.
Args:
nested_list (List[List[int]]): A nested... |
python_sharegpt_23k | 8,284 | Write a Python function to find the maximum value in an array while keeping track of the number of comparisons made during the search. The function should handle the case when the array is empty and should return `None` for the maximum value and `0` for the number of comparisons in such cases. The input array should ha... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def find_max_with_comparisons(arr: List[int]) -> Tuple[int, int]:
"""
Finds the maximum value in an array and counts the number of comparisons made during the search.
Args:
arr (List[... |
python_sharegpt_23k | 8,294 | Write a Python function to compute the sum of all positive even numbers in a given array. If the array does not contain any positive even numbers, return 0. The function should start with:
```python
from typing import List
def sum_positive_even_numbers(arr: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def sum_positive_even_numbers(arr: List[int]) -> int:
"""
Compute the sum of all positive even numbers in a given array.
Args:
arr (List[int]): The array of integers to process.
Returns... |
python_sharegpt_23k | 8,296 | Write a Python function to sort a list of numbers in descending order using a custom sorting algorithm that is not built-in or commonly used in programming languages. The custom sorting algorithm should be based on the selection sort algorithm.
The code should start with:
```python
from typing import List
def selecti... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def selection_sort_descending(numbers: List[int]) -> List[int]:
"""
Sorts a list of numbers in descending order using a custom selection sort algorithm.
Args:
numbers (List[int]): The list o... |
python_sharegpt_23k | 8,297 | Write a Python function called `remove_duplicates` that takes in a list of integers and removes any duplicate elements, while maintaining the order of the elements. The function should return the modified list. The original list should not be modified.
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 remove_duplicates(lst: List[int]) -> List[int]:
"""
Removes duplicate elements from a list of integers while preserving the order of the elements.
Args:
lst (List[int]): The input list o... |
python_sharegpt_23k | 8,300 | Write a Python function to find the longest common substring between two given strings. The function should return the longest contiguous sequence of characters that appears in both strings. The code should start with:
```python
def find_longest_common_substring(string1: str, string2: str) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
```python
def find_longest_common_substring(string1: str, string2: str) -> str:
"""
Find the longest common substring between two given strings.
Args:
string1 (str): The first input string.
string2 (str): The second i... |
python_sharegpt_23k | 8,302 | Write a Python function to delete the 4th element (index 3) from a given list efficiently. The list can contain up to 10,000 elements. The function should handle cases where the list has fewer than 4 elements and should not use any built-in functions or methods that directly delete elements from a list. The input list ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def delete_4th_element(lst: List[int]) -> List[int]:
"""
Deletes the 4th element (index 3) from the given list efficiently.
Args:
lst (List[int]): The list from which to delete the 4th eleme... |
python_sharegpt_23k | 8,305 | Write a Python function to count the number of times a given pattern occurs in a given string. The pattern can contain special characters and can be case-sensitive. The function should handle overlapping occurrences of the pattern.
The code should start with:
```python
def count_pattern_occurrences(text: str, pattern:... | Here is the Python code to solve the given problem in the markdown block:
```python
def count_pattern_occurrences(text: str, pattern: str) -> int:
"""
Counts the number of times a given pattern occurs in a given string, including overlapping occurrences.
Args:
text (str): The string in which to sea... |
python_sharegpt_23k | 8,310 | Write a Python function to analyze a set of numbers and return the number of positive numbers, the average of all positive numbers, the maximum positive number, and the minimum positive number. The function should handle up to \(10^6\) elements, where each element is an integer ranging from \(-10^9\) to \(10^9\).
The ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Tuple
def analyze_numbers(numbers: List[int]) -> Tuple[int, float, int, int]:
"""
Analyzes a set of numbers and returns the number of positive numbers,
the average of all positive numbers, the maxim... |
python_sharegpt_23k | 8,311 | Write a Python function to perform binary search on a sorted array and return the index of the target element. If the target element is not found, return -1. The function should be efficient and handle edge cases such as an empty array or a target that is outside the array's range.
The code should start with:
```pytho... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def binary_search(arr: List[int], target: int) -> int:
"""
Perform binary search on a sorted array to find the index of the target element.
If the target element is not found, return -1.
Args:
... |
python_sharegpt_23k | 8,321 | Write a Python function to find all prime numbers below a given limit `n`. The function should return a list of all prime numbers less than `n`.
The code should start with:
```python
from typing import List
def find_primes_below(n: 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_below(n: int) -> List[int]:
"""
Find all prime numbers below a given limit `n`.
Args:
n (int): The upper limit (exclusive) to find prime numbers below.
Retur... |
python_sharegpt_23k | 8,326 | Write a Python function to count the frequency of each character in a given string and return the result as a dictionary. Additionally, handle any erroneous inputs such as empty strings or non-string inputs by raising appropriate exceptions.
The code should start with:
```python
def count_character_frequency(input_str... | Here is the Python code to solve the given problem in the markdown block:
```python
def count_character_frequency(input_string: str) -> dict:
"""
Counts the frequency of each character in the given string and returns the result as a dictionary.
Args:
input_string (str): The input string for which c... |
python_sharegpt_23k | 8,327 | Write a Python function to find the second occurrence of a specific element in a given list efficiently. If the second occurrence is not found, the function should return `None`. The code should start with:
```python
from typing import List, Optional
def find_second_occurrence(lst: List[int], element: int) -> Optional... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def find_second_occurrence(lst: List[int], element: int) -> Optional[int]:
"""
Find the second occurrence of a specific element in a list.
Args:
lst (List[int]): The list in which ... |
python_sharegpt_23k | 8,328 | Write a Python function to retrieve the element at a given index in a 2D array. The function should convert the given 1D index to the corresponding 2D indices and return the element at that position. The code should start with:
```python
from typing import List
def get_element_at_index(array: List[List[int]], index: i... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def get_element_at_index(array: List[List[int]], index: int) -> int:
"""
Retrieves the element at the given 1D index in a 2D array.
Args:
array (List[List[int]]): The 2D array from which to ... |
python_sharegpt_23k | 8,332 | Write a Python function to sort a list of integers in ascending order using the Bubble Sort algorithm. The function should meet the following requirements:
1. The function should take a list of integers as input and return a sorted list in ascending order.
2. The function should use the Bubble Sort algorithm to sort th... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def bubble_sort(lst: List[int]) -> List[int]:
"""
Sorts a list of integers in ascending order using the Bubble Sort algorithm.
Args:
lst (List[int]): The list of integers to be sorted.
... |
python_sharegpt_23k | 8,335 | Write a Python function to extract common keywords from two given strings and return them in a sorted list without duplicates. The function should handle case-insensitive comparison and should not include punctuation in the comparison. The code should start with:
```python
from typing import List
def extract_common_ke... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import string
def extract_common_keywords(string1: str, string2: str) -> List[str]:
"""
Extracts common keywords from two given strings and returns them in a sorted list without duplicates.
Args:
... |
python_sharegpt_23k | 8,339 | Write a Python function to remove all consecutive duplicate characters from a given string in-place using a constant amount of additional space. The original string must be modified directly without creating a new string. The function should start with:
```python
def remove_consecutive_duplicates(string: str) -> str:
`... | Here is the Python code to solve the given problem in the markdown block:
```python
def remove_consecutive_duplicates(string: str) -> str:
"""
Removes all consecutive duplicate characters from the given string in-place.
Args:
string (str): The input string from which consecutive duplicates are to b... |
python_sharegpt_23k | 8,342 | Write a Python function to calculate the sum of all the odd numbers in a given list of integers. The function should have a time complexity of O(n) and a space complexity of O(1). The code should start with:
```python
from typing import List
def sum_of_odd_numbers(numbers: List[int]) -> int:
```
| Here is the Python code to solve the given problem in the markdown block:
:
```python
from typing import List
def sum_of_odd_numbers(numbers: List[int]) -> int:
"""
Calculate the sum of all odd numbers in the given list.
Args:
numbers (List[int]): A list of integers.
Returns:
int: The... |
python_sharegpt_23k | 8,343 | Write a Python function to filter out the even numbers from a given list of integers and return them sorted in ascending order. The function should handle an empty list and return an empty list in such cases. The code should start with:
```python
from typing import List
def get_even_numbers_sorted(input_list: List[int... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def get_even_numbers_sorted(input_list: List[int]) -> List[int]:
"""
Filters out the even numbers from the input list and returns them sorted in ascending order.
Args:
input_list (List[int])... |
python_sharegpt_23k | 8,344 | Write a Python function to remove all spaces and punctuation marks from a given sentence. The function should return the cleaned sentence as a string. The code should start with:
```python
import re
def clean_sentence(sentence: str) -> str:
```
| Here is the Python code to solve the given problem in the markdown block:
:
```python
import re
def clean_sentence(sentence: str) -> str:
"""
Removes all spaces and punctuation marks from the given sentence.
Args:
sentence (str): The input sentence from which spaces and punctuation marks are to be... |
python_sharegpt_23k | 8,345 | Write a Python function to extract and return only the uppercase characters from a given string. The function should ignore any punctuation or whitespace characters in the input string. Additionally, the function should not use any built-in Python functions or libraries that directly solve the problem (e.g., `str.isupp... | Here is the Python code to solve the given problem in the markdown block:
```python
def get_uppercase_chars(input_string: str) -> str:
"""
Extracts and returns only the uppercase characters from the given input string,
ignoring any punctuation or whitespace characters.
Args:
input_string (str):... |
python_sharegpt_23k | 8,346 | Write a Python function to determine if a given integer is a prime number. The function should have a time complexity of O(sqrt(n)), where n is the given integer. The function should return a boolean value indicating whether the number is prime or not.
The code should start with:
```python
import math
def is_prime(n:... | Here is the Python code to solve the given problem in the markdown block:
```python
import math
def is_prime(n: int) -> bool:
"""
Determines if a given integer is a prime number.
Args:
n (int): The integer to check for primality.
Returns:
bool: True if the integer is prime, False othe... |
python_sharegpt_23k | 8,348 | Write a Python function to determine if a given substring is present in a string and return the index at which the substring is found. If the substring is not found, return `False` and `-1`. The function should handle edge cases such as empty strings and substrings.
The code should start with:
```python
def find_subst... | Here is the Python code to solve the given problem in the markdown block:
```python
def find_substring(string: str, substring: str) -> tuple:
"""
Determines if a given substring is present in a string and returns the index at which the substring is found.
Args:
string (str): The string in which to ... |
python_sharegpt_23k | 8,359 | Write a Python function to generate a random array of integers within a specified range and length. The function should allow the user to specify the minimum and maximum values for the integers, as well as the length of the array. The code should start with:
```python
from typing import List
import random
def generate... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
import random
def generate_random_array(min_num: int, max_num: int, array_length: int) -> List[int]:
"""
Generates a random array of integers within a specified range and length.
Args:
min_n... |
python_sharegpt_23k | 8,361 | Write a Python function to iterate over a 2-dimensional list and return a list of strings where each string represents an element in the matrix in a specific format. The format should be "Element: <element>", where `<element>` is the value of the element in the matrix. The function should handle any size of the 2-dimen... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def format_matrix_elements(matrix: List[List[int]]) -> List[str]:
"""
Iterates over a 2-dimensional list and returns a list of strings where each string
represents an element in the matrix in the for... |
python_sharegpt_23k | 8,366 | Write a Python function to generate an array of length `n` where each element is the sum of its two preceding elements. The first two elements of the array should be `0` and `1`. If `n` is less than or equal to `0`, return an empty array. If `n` is `1`, return an array with only the first element. If `n` is `2`, return... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List
def generate_sum_array(n: int) -> List[int]:
"""
Generates an array of length n where each element is the sum of its two preceding elements.
The first two elements of the array are 0 and 1.
Args... |
python_sharegpt_23k | 8,370 | Write a Python function to calculate the factorial of a non-negative integer `n` using an iterative approach with a time complexity of O(n) and a space complexity of O(1). The function should handle invalid inputs (negative integers) by returning `None`.
The code should start with:
```python
def factorial_iterative(n:... | Here is the Python code to solve the given problem in the markdown block:
```python
def factorial_iterative(n: int) -> int:
"""
Calculate the factorial of a non-negative integer `n` using an iterative approach.
Args:
n (int): The non-negative integer for which to calculate the factorial.
Retur... |
python_sharegpt_23k | 8,372 | Write a Python function to implement the sequential search algorithm to find the minimum element in an array. The function should return the minimum element in the array.
The input array, `arr`, will contain `n` elements, where `1 <= n <= 10^6`. Each element in the array will be an integer between `1` and `10^6`. The ... | Here is the Python code to solve the given problem in the markdown block:
```python
from typing import List, Optional
def find_min(arr: List[int]) -> Optional[int]:
"""
Find the minimum element in the given array using the sequential search algorithm.
Args:
arr (List[int]): The input array contain... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.