source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
evol_instruct_66k
18,232
Write a Python function to calculate the range of values in a given list of integers. The range is defined as the difference between the maximum and minimum values in the list. The function should handle an empty list by returning `None`. The code should start with: ```python from typing import List, Optional def cal...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def calculate_range(numbers: List[int]) -> Optional[int]: """ Calculate the range of values in a given list of integers. The range is defined as the difference between the maximum and mini...
evol_instruct_66k
18,242
Write a Python function to generate a new list containing only the unique even numbers from a given list of integers, sorted in ascending order. The function should handle any list of integers, including empty lists and lists with no even numbers. The code should start with: ```python from typing import List def uniq...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def unique_even_numbers(numbers: List[int]) -> List[int]: """ Generates a new list containing only the unique even numbers from the given list of integers, sorted in ascending order. Args: n...
evol_instruct_66k
18,244
Write a Python function to calculate the conditional probability of event A occurring given that event B has occurred, using the provided probabilities of events A and B, and the conditional probability of event B occurring given that event A has occurred. The function should return the result rounded to three decimal ...
Here is the Python code to solve the given problem in the markdown block: ```python def calc_conditional_probability(prob_a: float, prob_b: float, cond_prob_b_given_a: float) -> float: """ Calculate the conditional probability of event A occurring given that event B has occurred. Args: prob_a (floa...
evol_instruct_66k
18,259
Write a Python function to determine if a given string contains every letter of the English alphabet at least once. The function should be case-insensitive and should ignore non-alphabetic characters. The code should start with: ```python def is_pangram(input_string: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_pangram(input_string: str) -> bool: """ Determine if the given string is a pangram (contains every letter of the English alphabet at least once). Args: input_string (str): The string to be checked. Retur...
evol_instruct_66k
18,270
Write a Python function to perform a lexical analysis on a given text, which involves counting the occurrences of each unique word after removing punctuation and converting the text to lowercase. The function should return a dictionary where the keys are the unique words and the values are their respective counts. The...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def lexical_analysis(text: str) -> Dict[str, int]: """ Perform a lexical analysis on the given text by counting the occurrences of each unique word. Args: text (str): The input text to analy...
evol_instruct_66k
18,293
Write a Python function to determine the smallest possible radius for a standard heater that ensures all houses are within the warmth radius of at least one heater. The function should take two lists as input: `houses` and `heaters`, where `houses` represents the locations of houses on a linear plane, and `heaters` rep...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import bisect def find_smallest_radius(houses: List[int], heaters: List[int]) -> int: """ Determine the smallest radius for heaters to ensure all houses are within the warmth radius of at least one heate...
evol_instruct_66k
18,301
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 a different word or phrase, typically using all the original letters exactly once. The function should ignore spaces and be case-insensitive. The code should start w...
Here is the Python code to solve the given problem in the markdown block: ```python def are_anagrams(string1: str, string2: str) -> bool: """ Determines if two given strings are anagrams of each other. Args: string1 (str): The first string to compare. string2 (str): The second string to com...
evol_instruct_66k
18,306
Write a Python function to generate a distinctive sequence of 12 characters using only the alphabetic elements 'x', 'y', and 'z', ensuring that no two consecutive characters in the sequence are the same. The function should start with: ```python from typing import List def generate_distinctive_sequence(length: int) ->...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def generate_distinctive_sequence(length: int) -> str: """ Generates a distinctive sequence of the specified length using the characters 'x', 'y', and 'z', ensuring that no two consecut...
evol_instruct_66k
18,314
Write a Python function to extract email addresses from an XML string using a regular expression. The function should be able to handle various email formats and ensure that only valid email addresses are extracted. The code should start with: ```python import re from typing import List def extract_emails_from_xml(xml...
Here is the Python code to solve the given problem in the markdown block: ```python import re from typing import List def extract_emails_from_xml(xml_str: str) -> List[str]: """ Extracts email addresses from an XML string using a regular expression. Args: xml_str (str): The XML string from which t...
evol_instruct_66k
18,317
Write a Python function to concatenate a list of strings with a specified delimiter. The function should handle cases where the list is empty or contains only one element. The code should start with: ```python from typing import List def concatenate_with_delimiter(string_list: List[str], delimiter: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def concatenate_with_delimiter(string_list: List[str], delimiter: str) -> str: """ Concatenates a list of strings with a specified delimiter. Args: string_list (List[str]): The list of str...
evol_instruct_66k
18,342
Write a Python function to compute the square root of each element in a given list without using any built-in or library functions for square root calculation. Additionally, implement a function to check if the calculated square root is an integer. If it is an integer, append the integer square root to a new list; othe...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def square_root(n: int) -> float: """ Compute the square root of a given number using the Babylonian method. Args: n (int): The number to compute the square root of. Returns: fl...
evol_instruct_66k
18,358
Write a Python function to simulate a simple countdown timer that counts down from a given number `n` to 1, printing each number as it counts down. The function should include a `break` statement to ensure the loop terminates after the countdown completes. The code should start with: ```python def countdown(n: int) ->...
Here is the Python code to solve the given problem in the markdown block: ```python def countdown(n: int) -> None: """ Simulates a countdown timer that counts down from a given number `n` to 1, printing each number as it counts down. The loop terminates after the countdown completes. Args: n (i...
evol_instruct_66k
18,360
Write a Python function to compute the value of Euler's number \( e \) using the infinite series definition. The series is given by: \[ e = \sum_{i=0}^{\infty} \frac{1}{i!} \] The function should take an integer `n` as input, which represents the number of terms to use in the series approximation. The function should...
Here is the Python code to solve the given problem in the markdown block: ```python import math def compute_eulers_number(n: int) -> float: """ Compute the value of Euler's number e using the first n terms of the infinite series definition. The series is defined as: e = sum(1 / i! for i in range(n)) ...
evol_instruct_66k
18,361
Write a Python function to traverse through a given list and return a new list containing the elements of the original list in reverse order. The function should handle lists of any length, including empty lists. The code should start with: ```python from typing import List def reverse_list(input_list: List[int]) -> L...
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]: """ Reverses the elements of the given list and returns the reversed list. Args: input_list (List[int]): The list of integers to be reve...
evol_instruct_66k
18,371
Write a Python function to convert a list of integers into a comma-separated string while maintaining the order of the integers. The function should handle any list of integers, including empty lists and lists with negative numbers. The code should start with: ```python from typing import List def convert_to_comma_sep...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def convert_to_comma_separated_string(numbers: List[int]) -> str: """ Converts a list of integers into a comma-separated string. Args: numbers (List[int]): A list of integers to be converted...
evol_instruct_66k
18,383
Write a Python function to convert a list of tuples into a dictionary where each tuple contains a name and a unique number, and the dictionary should use the unique numbers as keys and the names as values. The code should start with: ```python from typing import List, Tuple, Dict def convert_to_dict(tuples_list: List[...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def convert_to_dict(tuples_list: List[Tuple[str, str]]) -> Dict[str, str]: """ Converts a list of tuples into a dictionary where each tuple contains a name and a unique number. The dicti...
evol_instruct_66k
18,388
Write a Python function to create a 2-dimensional array (matrix) from a given sequence of integers. The function should take the sequence, the number of rows, and the number of columns as inputs, and return the 2-dimensional array. The sequence should be filled row by row. 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 create_2d_array(numbers: List[int], rows: int, cols: int) -> List[List[int]]: """ Create a 2-dimensional array from a given sequence of integers. Args: numbers (List[int]): The sequence ...
evol_instruct_66k
18,389
Write a Python function to calculate the arithmetic mean of a given numerical array. The function should handle arrays with zero length by returning `None`. The code should start with: ```python from typing import List, Optional def calculate_arithmetic_mean(array: List[float]) -> Optional[float]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def calculate_arithmetic_mean(array: List[float]) -> Optional[float]: """ Calculate the arithmetic mean of a given numerical array. Args: array (List[float]): The numerical array f...
evol_instruct_66k
18,394
Write a Python function to replace all even numbers in a given list with the string "Even". The function should take a list of integers as input and return a new list where all even numbers from the original list are replaced with the string "Even". The code should start with: ```python from typing import List def re...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def replace_even_numbers(nums: List[int]) -> List[str]: """ Replaces all even numbers in the given list with the string "Even". Args: nums (List[int]): The list of integers to process. ...
evol_instruct_66k
18,398
Write a Python function to search for a specific word in a list of words and return a message indicating whether the word was found or not. If the word is found, the function should return "Done". If the word is not found, the function should return "Word not found". The function should stop searching as soon as the wo...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def search_word(words: List[str], target: str) -> str: """ Searches for a specific word in a list of words and returns a message indicating whether the word was found or not. Args: words (Li...
evol_instruct_66k
18,411
Write a Python function to calculate the product of all distinct integers in a given list. The function should first identify and isolate all unique integers in the list, and then compute the multiplicative product of these unique integers. The code should start with: ```python from typing import List def product_of_d...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List from functools import reduce import operator def product_of_distinct_numbers(num_list: List[int]) -> int: """ Calculate the product of all distinct integers in a given list. Args: num_list (...
evol_instruct_66k
18,418
Write a Python function to create a dictionary that maps each month of the year to its average temperature in a given city. The function should take a list of tuples, where each tuple contains a month and its corresponding average temperature, and return a dictionary with the months as keys and the temperatures as valu...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def create_temperature_dict(temperatures: List[Tuple[str, int]]) -> dict: """ Creates a dictionary that maps each month of the year to its average temperature. Args: temperatures (Lis...
evol_instruct_66k
18,424
Write a Python function to expand a given list by duplicating each element in the list. The function should return a new list where each element from the original list appears twice consecutively. The code should start with: ```python from typing import List def expand_list(input_list: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def expand_list(input_list: List[int]) -> List[int]: """ Expands a given list by duplicating each element. Args: input_list (List[int]): The list of integers to be expanded. Returns: ...
evol_instruct_66k
18,425
Write a Python function to identify the final odd numeric element in a given array that is not a multiple of five. The function should iterate through the array and keep track of the last odd number that is not a multiple of five. If no such number exists, the function should return `None`. The code should start with:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def find_final_odd_not_multiple_of_five(array: List[int]) -> Optional[int]: """ Identify the final odd numeric element in the given array that is not a multiple of five. Args: arra...
evol_instruct_66k
18,429
Write a Python function to count the number of even integers in a given one-dimensional list of integers. The function should return the count of numbers that are divisible by 2. The code should start with: ```python from typing import List def count_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 count_even_numbers(arr: List[int]) -> int: """ Counts the number of even integers in a given list. Args: arr (List[int]): A list of integers. Returns: int: The count of even...
evol_instruct_66k
18,436
Write a Python function to securely store and retrieve employee information, including their IDs and emails, using a vector-based storage approach. The function should allow adding new employees, retrieving employee information by ID, and listing all stored employees. 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, Tuple, Optional def employee_management() -> Tuple[List[Tuple[int, str]], callable, callable, callable]: """ Manages employee information securely using a vector-based storage approach. Returns: ...
evol_instruct_66k
18,437
Write a Python function to reverse a given array of numbers. The function should take a list of integers as input and return a new list with the elements in reverse order. The function should not modify the original list. The code should start with: ```python from typing import List def reverse_array(arr: List[int]) ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_array(arr: List[int]) -> List[int]: """ Reverses the given array of numbers and returns a new list with the elements in reverse order. Args: arr (List[int]): The list of integers...
evol_instruct_66k
18,451
Write a Python function to generate a random alphanumeric string of a specified length. The string should consist of characters from the set of lowercase letters (a-z), uppercase letters (A-Z), and digits (0-9). The function should ensure that the generated string is exactly the specified length. The code should start...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random import string def generate_random_alphanumeric_string(length: int) -> str: """ Generates a random alphanumeric string of the specified length. Args: length (int): The length of...
evol_instruct_66k
18,455
Write a Python function to flatten a 3D matrix that contains a mix of integers and nested lists. The function should handle any level of nested lists and return a single list of all elements in a flattened form. The function should not use any built-in functions specifically designed for flattening lists. The code sho...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def flatten_3d_matrix(matrix: List[List[List[Any]]]) -> List[Any]: """ Flattens a 3D matrix containing a mix of integers and nested lists into a single list. Args: matrix: A 3D list con...
evol_instruct_66k
18,456
Write a Python function to generate a 2x2 matrix with elements localized within the range of -0.5 to 0.5, ensuring that the elements are populated randomly. The function should return the generated matrix. The code should start with: ```python import numpy as np def generate_random_matrix() -> np.ndarray: ```
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def generate_random_matrix() -> np.ndarray: """ Generates a 2x2 matrix with elements localized within the range of -0.5 to 0.5. Returns: np.ndarray: A 2x2 matrix with random elements between -0.5...
evol_instruct_66k
18,462
Write a Python function to remove an element from a list at a specified index if the index is valid. If the index is invalid, the function should return the original list without any changes. The function should start with: ```python from typing import List def remove_element_at_index(lst: List[int], index: int) -> Li...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def remove_element_at_index(lst: List[int], index: int) -> List[int]: """ Removes an element from the list at the specified index if the index is valid. Args: lst (List[int]): The list...
evol_instruct_66k
18,463
Write a Python function to calculate the total number of unique integers across multiple matrices. Each matrix is a 2D list of integers, and the function should return the count of unique integers present in all the matrices combined. The code should start with: ```python from typing import List def count_unique_inte...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_unique_integers(matrices: List[List[List[int]]]) -> int: """ Calculate the total number of unique integers across multiple matrices. Args: matrices (List[List[List[int]]]): A list ...
evol_instruct_66k
18,489
Write a Python function to calculate the cumulative sum of the digits of a given positive integer. The function should take a positive integer as input and return the sum of its individual digits. The code should start with: ```python def cumulative_sum_of_digits(num: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def cumulative_sum_of_digits(num: int) -> int: """ Calculate the cumulative sum of the digits of a given positive integer. Args: num (int): The positive integer whose digits' cumulative sum is to be calculated. ...
evol_instruct_66k
18,493
Write two Python functions, `calculate_circle_area` and `calculate_circle_circumference`, that calculate the area and circumference of a circle, respectively, given a radius. Both functions should raise a `ValueError` if the radius is not a positive number. The calculations should be accurate up to 5 decimal places and...
Here is the Python code to solve the given problem in the markdown block: ```python import math def calculate_circle_area(radius: float) -> float: """ Calculate the area of a circle given its radius. Args: radius (float): The radius of the circle. Returns: float: The area of the circl...
evol_instruct_66k
18,494
Write a Python function to generate all unique permutations of a given list of distinct alphanumeric characters. The function should be recursive and should return a list of all possible permutations. The code should start with: ```python from typing import List def get_all_permutations(lst: List[str]) -> List[List[st...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def get_all_permutations(lst: List[str]) -> List[List[str]]: """ Generate all unique permutations of a given list of distinct alphanumeric characters. Args: lst (List[str]): The list of dist...
evol_instruct_66k
18,497
Write a Python function to calculate the aggregate sum of a given array and another function to compute the sum of a subset of the array based on specified start and end indices. The array is provided as input to both functions. The code should start with: ```python from typing import List def aggregate_sum(array: Lis...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def aggregate_sum(array: List[int]) -> int: """ Calculate the aggregate sum of the given array. Args: array (List[int]): The array of integers to sum. Returns: int: The aggregat...
evol_instruct_66k
18,507
Write a Python function to convert a given tuple of strings into a list and then extract the second element from the list. The function should handle the conversion and extraction in a single step. The code should start with: ```python from typing import Tuple, List def extract_second_element(animals: Tuple[str, ...])...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple, List def extract_second_element(animals: Tuple[str, ...]) -> str: """ Converts a tuple of strings into a list and extracts the second element. Args: animals (Tuple[str, ...]): A tuple of s...
evol_instruct_66k
18,530
Write a Python function to generate the first `n` terms of the Fibonacci sequence using an iterative approach. The function should return a list of the first `n` Fibonacci numbers. 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 first n terms of the Fibonacci sequence using an iterative approach. Args: n (int): The number of Fibonacci terms to generate. ...
evol_instruct_66k
18,544
Write a Python function to calculate the sum of all elements in a given list of integers. The function should be efficient and handle lists of varying sizes. The code should start with: ```python from typing import List def calculate_sum_of_elements(array: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_sum_of_elements(array: List[int]) -> int: """ Calculate the sum of all elements in a given list of integers. Args: array (List[int]): The list of integers to sum. Returns:...
evol_instruct_66k
18,546
Write a Python function to transform a list of words into a unified text string, using commas as separators between individual words, without using the built-in `join()` function. The function should handle any list of strings and ensure that the final string does not end with a comma. The code should start with: ```p...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def list_to_string(word_list: List[str]) -> str: """ Transforms a list of words into a unified text string with commas as separators. Args: word_list (List[str]): A list of words to be trans...
evol_instruct_66k
18,549
Write a Python function to compute the transpose of a given m x n matrix. The transpose of a matrix is obtained by swapping its rows with its columns. The function should handle matrices of any size, including non-square matrices. The code should start with: ```python from typing import List def transpose_matrix(matr...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def transpose_matrix(matrix: List[List[int]]) -> List[List[int]]: """ Compute the transpose of a given matrix. Args: matrix (List[List[int]]): The input matrix to be transposed. Returns...
evol_instruct_66k
18,555
Write a Python function to construct a new array where each element is the factorial of the corresponding element in the original array. The function should handle arrays with non-negative integers only. The code should start with: ```python from typing import List import math def factorial_array(arr: List[int]) -> Li...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def factorial_array(arr: List[int]) -> List[int]: """ Constructs a new array where each element is the factorial of the corresponding element in the original array. Args: arr (Li...
evol_instruct_66k
18,559
Write a Python function to find the maximum value among three given integers without using the built-in `max` function. The function should compare the integers manually and return the highest value. The code should start with: ```python def find_max_of_three(num1: int, num2: int, num3: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def find_max_of_three(num1: int, num2: int, num3: int) -> int: """ Find the maximum value among three given integers. Args: num1 (int): The first integer. num2 (int): The second integer. num3 (int): ...
evol_instruct_66k
18,565
Write a Python function to randomly select a single term from a given list of terms. The function should ensure that each term has an equal probability of being selected. The code should start with: ```python from typing import List import random def select_random_term(terms: List[str]) -> str: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List import random def select_random_term(terms: List[str]) -> str: """ Randomly selects a single term from a given list of terms. Args: terms (List[str]): A list of terms from which to select ...
evol_instruct_66k
18,567
Write a Python function to obtain an ascending order list without any repeated values from a given list of integers. The function should handle lists with duplicate values and return a sorted list with unique elements. The code should start with: ```python from typing import List def unique_sorted_list(lst: List[int])...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def unique_sorted_list(lst: List[int]) -> List[int]: """ Returns a sorted list of unique elements from the given list. Args: lst (List[int]): The list of integers from which to extract uniqu...
evol_instruct_66k
18,570
Write a Python function to encrypt a given UTF-8 delimited text-based series of characters using a Caesar Cipher algorithm. The function should handle both uppercase and lowercase letters, and leave non-alphabetic characters unchanged. The code should start with: ```python def caesar_cipher_encrypt(text: str, shift: in...
Here is the Python code to solve the given problem in the markdown block: ```python def caesar_cipher_encrypt(text: str, shift: int) -> str: """ Encrypts a given text using a Caesar Cipher algorithm. Args: text (str): The text to be encrypted. shift (int): The number of positions to shift e...
evol_instruct_66k
18,583
Write a Python function to detect and count the number of Unicode whitespace characters within a given input text. The function should also identify the type of each whitespace character (e.g., tab, line feed, space, etc.) and organize the information in a sorted dictionary where each key-value pair represents the type...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Tuple import collections def count_whitespaces(input_text: str) -> None: """ Detects and counts the number of Unicode whitespace characters within a given input text. Identifies the type of ea...
evol_instruct_66k
18,588
Write a Python function to retrieve the last element from a given list of integers. If the list is empty, the function should return `None`. The function should be efficient and handle edge cases appropriately. The code should start with: ```python from typing import List, Optional def get_last_element(lst: List[int]...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def get_last_element(lst: List[int]) -> Optional[int]: """ Retrieves the last element from a given list of integers. Args: lst (List[int]): The list of integers from which to retri...
evol_instruct_66k
18,593
Write a Python function to generate the Fibonacci sequence up to the nth ordinal number position using an iterative approach. The function should return a list containing the Fibonacci sequence up to the nth position. The code should start with: ```python from typing import List def generate_fibonacci(n: int) -> List[...
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 ordinal number position using an iterative approach. Args: n (int): The ordinal number position...
evol_instruct_66k
18,600
Write a Python function to calculate the factorial of a given non-negative integer `n`. The factorial of a number `n` (denoted as `n!`) is the product of all positive integers less than or equal to `n`. The function should handle edge cases such as `n = 0` and `n = 1` correctly. The code should start with: ```python d...
Here is the Python code to solve the given problem in the markdown block: ```python def factorial(n: int) -> int: """ Calculate the factorial of a given non-negative integer n. Args: n (int): The non-negative integer for which to calculate the factorial. Returns: int: The factorial of ...
evol_instruct_66k
18,606
Write a Python function to sort a given tuple of integers in descending order. The function should return a new tuple with the elements sorted in descending order. The original tuple should remain unchanged. The code should start with: ```python from typing import Tuple def sort_tuple_descending(input_tuple: Tuple[in...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple def sort_tuple_descending(input_tuple: Tuple[int, ...]) -> Tuple[int, ...]: """ Sorts a given tuple of integers in descending order and returns a new tuple. Args: input_tuple (Tuple[int, .....
evol_instruct_66k
18,607
Write a Python function to calculate the average of a list of numbers, ensuring that the function handles edge cases such as an empty list and non-numeric values. The function should return `None` if the list is empty or contains non-numeric values. The code should start with: ```python from typing import List, Union ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def calculate_average(numbers: List[Union[int, float]]) -> Union[float, None]: """ Calculate the average of a list of numbers. Args: numbers (List[Union[int, float]]): A list of numbe...
evol_instruct_66k
18,608
Write a Python function to substitute each occurrence of the character '0' with the character 'x' in a given 2D matrix consisting of character elements. The function should modify the matrix in place and return the modified matrix. The code should start with: ```python from typing import List def replace_zeros_with_x...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def replace_zeros_with_x(matrix: List[List[str]]) -> List[List[str]]: """ Substitutes each occurrence of the character '0' with the character 'x' in a given 2D matrix. Args: matrix (List[Lis...
evol_instruct_66k
18,611
Write a Python function to remove all occurrences of a specified element from a given list. The function should return a new list with all instances of the specified element removed. The original list should not be modified. The code should start with: ```python from typing import List def remove_all_occurrences(arr:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_all_occurrences(arr: List[int], element: int) -> List[int]: """ Removes all occurrences of the specified element from the given list. Args: arr (List[int]): The list from which to...
evol_instruct_66k
18,612
Write a Python function to find all unique combinations of elements from a given list, ensuring that each combination is unique and that the function can handle large input lists efficiently. The function should avoid repetition of equivalent combinations and should return a set of tuples representing these unique comb...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Set, Tuple from itertools import combinations def unique_combinations(input_list: List[int]) -> Set[Tuple[int]]: """ Find all unique combinations of elements from the given list. Args: inpu...
evol_instruct_66k
18,626
Write a Python function to trim a string by removing leading and trailing whitespace characters, as well as extra spaces between words. The function should return the cleaned string. The code should start with: ```python def trim_string(s: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def trim_string(s: str) -> str: """ Trims a string by removing leading and trailing whitespace characters, as well as extra spaces between words. Args: s (str): The input string to be trimmed. Returns: ...
evol_instruct_66k
18,634
Write a Python function to determine the specific day of the week for a given date and calculate the number of days until the next occurrence of the same weekday. The date is provided as three separate integers representing the `day`, `month`, and `year`. The function should return a tuple where the first element is th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple import datetime def get_weekday_and_next_occurrence(day: int, month: int, year: int) -> Tuple[str, int]: """ Determine the weekday for a given date and calculate the number of days until the next occurr...
evol_instruct_66k
18,648
Write a Python function to calculate the frequency of each unique word in a given paragraph. The function should handle punctuation by removing it and should return a dictionary where the keys are the unique words and the values are their respective frequencies. 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 Dict def word_frequency(paragraph: str) -> Dict[str, int]: """ Calculate the frequency of each unique word in a given paragraph. Args: paragraph (str): The input paragraph from which to calculate...
evol_instruct_66k
18,649
Write a Python function to extract the domain component from an email address following the format: `email = "username@domain.com"`. The function should handle various email formats and return the domain part of the email address. The code should start with: ```python def extract_domain(email: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def extract_domain(email: str) -> str: """ Extracts the domain component from an email address. Args: email (str): The email address from which to extract the domain. Returns: str: The domain part of th...
evol_instruct_66k
18,673
Write a Python function to find the minimum number of disjoint time periods required to cover the entire range of a given series of time periods. Each time period is represented as a list of two integers `[start, end]`, where `start` is the beginning of the period and `end` is the end of the period. The function should...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def min_disjoint_periods(periods: List[List[int]]) -> List[List[int]]: """ Find the minimum number of disjoint time periods required to cover the entire range of a given series of time periods. Args...
evol_instruct_66k
18,681
Write a Python function to convert a 3-dimensional NumPy array into a 2-dimensional array by flattening the first two dimensions. The function should take a 3-dimensional NumPy array as input and return a 2-dimensional NumPy array. The code should start with: ```python import numpy as np def flatten_3d_to_2d(arr: np....
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def flatten_3d_to_2d(arr: np.ndarray) -> np.ndarray: """ Converts a 3-dimensional NumPy array into a 2-dimensional array by flattening the first two dimensions. Args: arr (np.ndarray): A 3-dimens...
evol_instruct_66k
18,701
Write a Python function to count the number of occurrences of a specified character in a given string without using any built-in string functions or methods. The function should iterate through the string and count the occurrences manually. The code should start with: ```python def count_occurrences(string: str, char:...
Here is the Python code to solve the given problem in the markdown block: ```python def count_occurrences(string: str, char: str) -> int: """ Counts the number of occurrences of a specified character in a given string. Args: string (str): The string in which to count the occurrences. char (...
evol_instruct_66k
18,704
Write a Python function to generate a numerical sequence of all positive integers starting from 1 and ending at a given number `n`. The sequence should be formatted as a single string with each number separated by a comma and a space. The function should handle the edge case where `n` is less than 1 by returning an emp...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_sequence(n: int) -> str: """ Generate a numerical sequence of all positive integers starting from 1 and ending at `n`. The sequence is formatted as a single string with each number separated by a comma and a spa...
evol_instruct_66k
18,705
Write a Python function to implement the Merge Sort algorithm for sorting a 2D array in row-major order. The function should take a 2D list of integers as input and return the sorted 2D list. The sorting should be done by considering the elements in row-major order, i.e., treating the 2D array as a 1D array where eleme...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sort_2d(arr: List[List[int]]) -> List[List[int]]: """ Sorts a 2D array in row-major order using the Merge Sort algorithm. Args: arr (List[List[int]]): The 2D array to be sorted. ...
evol_instruct_66k
18,741
Write a Python function to generate a random number within a specified range. The function should take two integers, `min_value` and `max_value`, as input and return a random integer within the inclusive range `[min_value, max_value]`. The function should handle edge cases such as when `min_value` is greater than `max_...
Here is the Python code to solve the given problem in the markdown block: ```python import random def generate_random_number(min_value: int, max_value: int) -> int: """ Generates a random integer within the inclusive range [min_value, max_value]. Args: min_value (int): The lower bound of the range...
evol_instruct_66k
18,759
Write a Python function to calculate the final value of a variable `x` after performing a series of arithmetic operations on it. The operations involve doubling the value of `x` and then adding the result to itself. The function should take an initial value of `x` as input and return the final value after the operation...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_final_value(initial_value: int) -> int: """ Calculate the final value of a variable `x` after performing a series of arithmetic operations. The operations involve doubling the value of `x` and then adding the ...
evol_instruct_66k
18,760
Write a Python function to find the index of a specific element in a given list of letters. The function should return the index of the first occurrence of the specified element. If the element is not found, the function should return -1. The code should start with: ```python from typing import List def find_letter_i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_letter_index(letters: List[str], target: str) -> int: """ Find the index of the first occurrence of the target element in the given list of letters. Args: letters (List[str]): The l...
evol_instruct_66k
18,772
Write a Python function to check if a given directory exists, calculate the number of files and subdirectories within it, and display the result along with the directory path. Additionally, if the directory contains any file with a specific file extension (such as ".txt"), count the number of such files and display the...
Here is the Python code to solve the given problem in the markdown block: ```python import os def analyze_directory(dir_path: str, file_extension: str = ".txt") -> None: """ Analyzes the given directory to count the number of files, subdirectories, and files with a specific extension. Args: dir_pa...
evol_instruct_66k
18,793
Write a Python function to delete an element from a specific index in a three-dimensional list. The function should take a three-dimensional list and a position (a list of three integers) as inputs and return a new three-dimensional list with the element at the specified position removed. 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 delete_element_3d(array: List[List[List[int]]], position: List[int]) -> List[List[List[int]]]: """ Deletes an element from a specific index in a three-dimensional list. Args: array (List...
evol_instruct_66k
18,801
Write a Python function to find and return the second smallest element in a given list of integers. If the list has fewer than two elements, the function should return `None`. The function should handle duplicate values by considering only unique values. The code should start with: ```python from typing import List, O...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def find_second_smallest(nums: List[int]) -> Optional[int]: """ Find and return the second smallest element in a given list of integers. Args: nums (List[int]): The list of integer...
evol_instruct_66k
18,814
Write a Python function to perform numerical subtraction between two given numbers. The function should handle both positive and negative numbers, as well as zero. The code should start with: ```python def subtract_two_numbers(a: float, b: float) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python def subtract_two_numbers(a: float, b: float) -> float: """ Perform numerical subtraction between two given numbers. Args: a (float): The first number. b (float): The second number. Returns: floa...
evol_instruct_66k
18,816
Write a Python function to determine if a given string contains the characters "C", "D", and "E" exactly once each, in any order, and is case-insensitive. Additionally, the total length of the matched string should not exceed 10 characters. The code should start with: ```python import re def match_CDE_once(string: st...
Here is the Python code to solve the given problem in the markdown block: ```python import re def match_CDE_once(string: str) -> bool: """ Determine if the given string contains the characters "C", "D", and "E" exactly once each, in any order, and is case-insensitive. The total length of the string should ...
evol_instruct_66k
18,827
Write a Python function to classify a given data point using the k-Nearest Neighbors (k-NN) algorithm with k=3. The function should take a list of training data points (each represented as a tuple of features and a label) and a test data point (represented as a tuple of features) as input, and return the predicted labe...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple import heapq def classify_knn(training_data: List[Tuple[List[float], str]], test_point: List[float]) -> str: """ Classify a given test point using the k-Nearest Neighbors algorithm with k=3. ...
evol_instruct_66k
18,835
Write a Python function to compute the average temperature of a given set of temperatures. The function should handle an empty list by returning `None` and should return the average temperature rounded to two decimal places for non-empty lists. The code should start with: ```python from typing import List, Optional d...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def compute_average_temperature(temperatures: List[float]) -> Optional[float]: """ Compute the average temperature of a given set of temperatures. Args: temperatures (List[float]):...
evol_instruct_66k
18,836
Write a Python function to perform ternary search on a sorted list. The function should return the index of the key if it is present in the list, otherwise return -1. The function should be recursive and should use the ternary search algorithm, which divides the list into three parts instead of two as in binary search....
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def ternary_search(l: int, r: int, key: int, ar: List[int]) -> int: """ Perform a ternary search on a sorted list to find the index of the key. Args: l (int): The left index of the current s...
evol_instruct_66k
18,852
Write a Python function to generate an HTML form based on the attributes and values specified in a given dictionary. The dictionary should include the form's fields (as keys) and their corresponding values. The function should return a string containing the HTML form. 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 Dict def generate_html_form(form_data: Dict[str, str]) -> str: """ Generates an HTML form based on the attributes and values specified in the given dictionary. Args: form_data (Dict[str, str]): A...
evol_instruct_66k
18,856
Write a Python function to generate a square matrix of size `n x n` filled with Fibonacci numbers. The function should start with: ```python from typing import List def generate_fibonacci_matrix(n: int) -> List[List[int]]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_fibonacci_matrix(n: int) -> List[List[int]]: """ Generates a square matrix of size n x n filled with Fibonacci numbers. Args: n (int): The size of the matrix (n x n). Retur...
evol_instruct_66k
18,857
Write a Python function to extract the last n elements from a given list of unique elements. The function should handle cases where n is greater than the length of the list by returning the entire list. The function should also handle cases where n is less than or equal to zero by returning an empty list. The code sho...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def get_last_n_elements(elements: List[int], n: int) -> List[int]: """ Extracts the last n elements from the given list of unique elements. Args: elements (List[int]): The list of unique ele...
evol_instruct_66k
18,862
Write a Python function to classify data points using a Radius Neighbors Classifier with a non-Euclidean distance metric. The function should take a training dataset, a test dataset, a radius, and a distance metric function as inputs, and return the predicted labels for the test dataset. The distance metric function sh...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Callable from collections import Counter def radius_neighbors_classifier(train_data: List[List[float]], train_labels: List[int], test_data: List[List[float]], radius: float, distance_metric: Callable[[List[floa...
evol_instruct_66k
18,905
Write a Python function to determine whether a given integer is a prime number. The function should efficiently check for primality by considering only potential divisors up to the square root of the number. The function should handle edge cases such as negative numbers, zero, and one, which are not prime numbers. The...
Here is the Python code to solve the given problem in the markdown block: ```python from math import sqrt def is_prime(n: int) -> bool: """ Determine whether a given integer is a prime number. Args: n (int): The integer to check for primality. Returns: bool: True if the integer is pri...
evol_instruct_66k
18,949
Write a Python function to find both the minimum value and its index position within a given tuple of 22 elements. Do not use any built-in functions like `min()` or `index()` for this task. The function should start with: ```python def find_min_value_and_index(T: tuple) -> tuple: ```
Here is the Python code to solve the given problem in the markdown block: ```python def find_min_value_and_index(T: tuple) -> tuple: """ Find the minimum value and its index position within a given tuple of 22 elements. Args: T (tuple): A tuple of 22 elements. Returns: tuple: A tuple c...
evol_instruct_66k
18,972
Write a Python function to merge two lists, ensuring that the resulting list contains no duplicates and is sorted in ascending order. The function should start with: ```python from typing import List def merge_sorted_unique_lists(list_1: List[int], list_2: 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_sorted_unique_lists(list_1: List[int], list_2: List[int]) -> List[int]: """ Merges two lists, ensuring the resulting list contains no duplicates and is sorted in ascending order. Args: ...
evol_instruct_66k
18,974
Write a Python function to convert a temperature from Fahrenheit to Celsius. The function should take a single argument representing the temperature in Fahrenheit and return the equivalent temperature in Celsius. The conversion formula is: \[ \text{Celsius} = \frac{(\text{Fahrenheit} - 32) \times 5}{9} \] The code sh...
Here is the Python code to solve the given problem in the markdown block: ```python def fahrenheit_to_celsius(fahrenheit: float) -> float: """ Converts a temperature from Fahrenheit to Celsius. Args: fahrenheit (float): The temperature in Fahrenheit to be converted. Returns: float: The...
evol_instruct_66k
18,979
Write a Python function to systematically shuffle the elements within a provided list, ensuring a distinct and random permutation. The function should return the shuffled list. The code should start with: ```python from typing import List import random def shuffle_list(nums: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def shuffle_list(nums: List[int]) -> List[int]: """ Shuffles the elements within the provided list, ensuring a distinct and random permutation. Args: nums (List[int]): The list...
evol_instruct_66k
18,993
Write a Python function to validate whether a given string is a legitimate IP address (both IPv4 and IPv6). The function should use regular expressions to determine the validity of the IP address. The function should return `True` if the IP address is valid and `False` if it is not. The code should start with: ```pytho...
Here is the Python code to solve the given problem in the markdown block: ```python import re def validate_ip(ip_address: str) -> bool: """ Validate whether the given string is a legitimate IP address (IPv4 or IPv6). Args: ip_address (str): The IP address string to validate. Returns: ...
evol_instruct_66k
18,997
Write a Python function to convert a binary tree into a doubly-linked list (DLL) in-place. The DLL should be in the same order as an in-order traversal of the binary tree. The function should return the head of the DLL. The code should start with: ```python class TreeNode: def __init__(self, value=0, left=None, ri...
Here is the Python code to solve the given problem in the markdown block: ```python class TreeNode: def __init__(self, value=0, left=None, right=None): self.value = value self.left = left self.right = right def convert_binary_tree_to_dll(root: TreeNode) -> TreeNode: """ Convert a bi...
evol_instruct_66k
19,002
Write a Python function to find the common elements between two lists of integers. The function should return a list of these common elements in ascending order. The code should start with: ```python from typing import List def find_common_elements(arr1: List[int], arr2: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_common_elements(arr1: List[int], arr2: List[int]) -> List[int]: """ Find the common elements between two lists of integers and return them in ascending order. Args: arr1 (List[int])...
evol_instruct_66k
19,015
Write a Python function to determine which of the two input words is lexicographically greater. The function should return the greater word. If the words are equal, it should return either word. The code should start with: ```python def find_greater_word(word1: str, word2: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def find_greater_word(word1: str, word2: str) -> str: """ Determines which of the two input words is lexicographically greater. Args: word1 (str): The first word to compare. word2 (str): The second word to c...
evol_instruct_66k
19,036
Write a Python function to compute the total quantity of unique, uninterrupted sub-sequences in a given string. The function should handle various types of characters, including alphabetic characters, punctuation, whitespace, and numbers. Repeating sequences should be counted only once. The code should start with: ```...
Here is the Python code to solve the given problem in the markdown block: ```python def count_unique_subsequences(string: str) -> int: """ Computes the total quantity of unique, uninterrupted sub-sequences in a given string. Args: string (str): The input string from which to compute the sub-sequenc...
evol_instruct_66k
19,046
Write a Python function to find the numerical position of the singleton element in a given list of integers. A singleton element is an element that appears exactly once in the list. The function should handle negative numbers and zero. The code should start with: ```python from typing import List def find_singleton_po...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_singleton_position(arr: List[int]) -> int: """ Find the position of the singleton element in a given list of integers. Args: arr (List[int]): The list of integers to search for the ...
evol_instruct_66k
19,057
Write a Python function to create a 2D array that combines a list of student names with their corresponding GPAs. The function should return the combined 2D array. The code should start with: ```python from typing import List, Tuple def combine_students_gpas(students: List[str], gpas: List[float]) -> List[Tuple[str, f...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def combine_students_gpas(students: List[str], gpas: List[float]) -> List[Tuple[str, float]]: """ Combines a list of student names with their corresponding GPAs into a 2D array. Args: ...
evol_instruct_66k
19,062
Write a Python function to iterate over the characters in a given text string and return a list of these characters in the order they are encountered. The function should handle any non-empty string input. The code should start with: ```python from typing import List def get_characters_list(text: str) -> List[str]: `...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def get_characters_list(text: str) -> List[str]: """ Returns a list of characters from the given text string in the order they are encountered. Args: text (str): The input string to iterate ...
evol_instruct_66k
19,064
Write a Python function to calculate the nth number in the Lucas sequence using dynamic programming. The Lucas sequence is defined as: - L(0) = 2 - L(1) = 1 - L(n) = L(n-1) + L(n-2) for n >= 2 The function should efficiently compute the nth Lucas number and provide an analysis of the time and space complexity of the s...
Here is the Python code to solve the given problem in the markdown block: ```python def lucas_number(n: int) -> int: """ Calculate the nth number in the Lucas sequence using dynamic programming. The Lucas sequence is defined as: - L(0) = 2 - L(1) = 1 - L(n) = L(n-1) + L(n-2) for n >= 2 Arg...
evol_instruct_66k
19,065
Write a Python function to perform a binary search on a sorted integer array and return the index of the target value if it exists in the array, otherwise return -1. The function should be efficient and use the divide-and-conquer approach. The code should start with: ```python from typing import List def binary_searc...
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 a binary search on a sorted integer array to find the index of the target value. Args: arr (List[int]): A sorted list of in...
evol_instruct_66k
19,071
Write a Python function to calculate the sum of the digits of a given integer. The function should handle both positive and negative integers. The code should start with: ```python def sum_of_digits(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def sum_of_digits(n: int) -> int: """ Calculate the sum of the digits of a given integer. Args: n (int): The integer whose digits are to be summed. Returns: int: The sum of the digits of the integer. ...
evol_instruct_66k
19,084
Write a Python function to reverse the elements of a given list. The function should return a new list with the elements in reverse order without modifying the original list. The code should start with: ```python from typing import List def reverse_list(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 reverse_list(arr: List[int]) -> List[int]: """ Returns a new list with the elements of the input list in reverse order. Args: arr (List[int]): The list of integers to be reversed. ...
evol_instruct_66k
19,098
Write a Python function to find the nth term in a geometric sequence given the first term, the common ratio, and the position of the term in the sequence. The function should return the nth term as an integer. The code should start with: ```python def find_nth_term_in_geometric_sequence(first_term: int, common_ratio: ...
Here is the Python code to solve the given problem in the markdown block: ```python def find_nth_term_in_geometric_sequence(first_term: int, common_ratio: int, n: int) -> int: """ Calculate the nth term in a geometric sequence. Args: first_term (int): The first term of the geometric sequence. ...
evol_instruct_66k
19,101
Write a Python function to sort a dictionary based on its values in ascending order, while maintaining the key-value pairs. The function should return the sorted dictionary. The code should start with: ```python from typing import Dict def sort_dict_by_value(d: Dict[str, int]) -> Dict[str, int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def sort_dict_by_value(d: Dict[str, int]) -> Dict[str, int]: """ Sorts a dictionary by its values in ascending order while maintaining the key-value pairs. Args: d (Dict[str, int]): The dict...
evol_instruct_66k
19,102
Write a Python function to compute the least common multiple (LCM) of three given integers. The function should be efficient and leverage the greatest common divisor (GCD) to calculate the LCM. The code should start with: ```python import math def lcm_of_three(x: int, y: int, z: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python import math def lcm_of_three(x: int, y: int, z: int) -> int: """ Compute the least common multiple (LCM) of three integers. Args: x (int): The first integer. y (int): The second integer. z (int): Th...
evol_instruct_66k
19,104
Write a Python function to reverse a given string and return the reversed string. The function should handle any non-empty string input. 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 and returns the reversed string. Args: s (str): The input string to be reversed. Returns: str: The reversed string. """ # Ensur...