source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
evol_instruct_66k
20,804
Write a Python function to find the k lowest even numbers from a given dataset efficiently. The dataset is a list of integers. The function should use an efficient sorting algorithm to achieve this. Additionally, provide a piece of faulty code where a simple sorting mechanism is incorrectly applied leading to wrong out...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import heapq def get_k_lowest_even_numbers(dataset: List[int], k: int) -> List[int]: """ Returns the k lowest even numbers from the given dataset. Args: dataset (list): The dataset from whic...
evol_instruct_66k
20,810
Write a Python function that processes a list of elements using a `while` loop. The function should square each numeric element and store the result in a new list. If an element is not numeric, it should handle the exception by printing an error message and continue processing the rest of the list. The function should ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def process_list(arr: List[int]) -> List[int]: """ Processes a list of elements, squares each numeric element, and stores the result in a new list. If an element is not numeric, it prints an error me...
evol_instruct_66k
20,811
Write a Python function to construct a dictionary from a list of tuples, where each tuple contains a key-value pair. The function should handle cases where the list might be empty or contain duplicate keys. If there are duplicate keys, the function should retain the last occurrence of each key in the resulting dictiona...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def construct_dictionary(pairs: List[Tuple[str, int]]) -> Dict[str, int]: """ Constructs a dictionary from a list of tuples, where each tuple contains a key-value pair. If there are dupl...
evol_instruct_66k
20,813
Write a Python function to convert a string of comma-separated numerical integers into a list of integers, shuffle the list to randomize the order of its elements, and return the shuffled list. The function should handle input validation to ensure the input string contains only valid numerical integers separated by com...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def shuffle_numbers(input_string: str) -> List[int]: """ Converts a string of comma-separated numerical integers into a list of integers, shuffles the list to randomize the order of its...
evol_instruct_66k
20,818
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 be case-insensitive and should ignore spaces. The code should ...
Here is the Python code to solve the given problem in the markdown block: ```python def are_anagrams(str1: str, str2: str) -> bool: """ Determines if two given strings are anagrams of each other. Args: str1 (str): The first string to compare. str2 (str): The second string to compare. R...
evol_instruct_66k
20,821
Write a Python function to determine if a given number is a prime number between 1 and 30. The function should return `True` if the number is a prime number within this range, and `False` otherwise. The code should start with: ```python def is_prime_in_range(number: int) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime_in_range(number: int) -> bool: """ Determine if a given number is a prime number between 1 and 30. Args: number (int): The number to check. Returns: bool: True if the number is a prime numb...
evol_instruct_66k
20,822
Write a Python function to determine if one string is a subsequence of another string. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. The function should return `True` if the first string is a subsequence of the...
Here is the Python code to solve the given problem in the markdown block: ```python def is_subsequence(str1: str, str2: str) -> bool: """ Determines if the first string is a subsequence of the second string. Args: str1 (str): The string to check if it is a subsequence. str2 (str): The strin...
evol_instruct_66k
20,839
Write a Python function to sort a given list of complex numbers based on their magnitudes in increasing order. The function should take a list of complex numbers as input and return the sorted list. The code should start with: ```python from typing import List def sort_complex_numbers_by_magnitude(complex_list: List[c...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_complex_numbers_by_magnitude(complex_list: List[complex]) -> List[complex]: """ Sorts a given list of complex numbers based on their magnitudes in increasing order. Args: complex_li...
evol_instruct_66k
20,842
Write a Python function to find all indices of elements in a given list that match a specified search query. The function should return a list of indices where each index corresponds to an element in the list that matches the search query. The code should start with: ```python from typing import List def find_all_ind...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_all_indices(lst: List[str], search_query: str) -> List[int]: """ Find all indices of elements in the list that match the search query. Args: lst (List[str]): The list of strings to ...
evol_instruct_66k
20,847
Write a Python function to check if a given string has balanced parentheses, including round, square, and curly braces. The function should ensure that each opening bracket has a corresponding closing bracket in the correct order. The code should start with: ```python def is_balanced_parentheses(s: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_balanced_parentheses(s: str) -> bool: """ Check if a given string has balanced parentheses, including round, square, and curly braces. Args: s (str): The string to check for balanced parentheses. Returns...
evol_instruct_66k
20,851
Write a Python function to flatten a multi-dimensional nested list into a single, flat list. The function should handle varying levels of nested lists, such as lists within lists within lists, and maintain the relative order of the elements in the flat output. The function should not use any external libraries or built...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def flatten_list(nested_list: List[Any]) -> List[Any]: """ Flattens a multi-dimensional nested list into a single, flat list. Args: nested_list (List[Any]): The input list, which may co...
evol_instruct_66k
20,853
Write a Python function to determine if a given string is a valid palindrome considering only alphanumeric characters and ignoring cases. The function should return `True` if the string is a valid palindrome, otherwise `False`. The code should start with: ```python def is_valid_palindrome(s: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_valid_palindrome(s: str) -> bool: """ Determine if a given string is a valid palindrome considering only alphanumeric characters and ignoring cases. Args: s (str): The input string to be checked. Returns...
evol_instruct_66k
20,855
Write a Python function to perform arithmetic subtraction on two numeric inputs, where the second number is subtracted from the first number. The function should handle both integer and float inputs. The code should start with: ```python def subtract(num1: float, num2: float) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python def subtract(num1: float, num2: float) -> float: """ Perform arithmetic subtraction by subtracting the second number from the first number. Args: num1 (float): The first number, from which the second number will be ...
evol_instruct_66k
20,865
Write a Python function to sort a given list of numbers using the Bubble Sort algorithm. The function should return the sorted list. The code should start with: ```python from typing import List def bubble_sort(nums: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def bubble_sort(nums: List[int]) -> List[int]: """ Sorts a given list of numbers using the Bubble Sort algorithm. Args: nums (List[int]): The list of numbers to be sorted. Returns: ...
evol_instruct_66k
20,868
Write a Python function to remove all instances of a specified numerical value from a given list of integers. The function should return a new list with all occurrences of the specified value removed. The function should handle the input in a way that avoids modifying the original list. The code should start with: ```...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def remove_value(nums: List[int], value: Dict[str, int]) -> List[int]: """ Removes all instances of a specified numerical value from a given list of integers. Args: nums (List[int]): T...
evol_instruct_66k
20,875
Write a Python function to calculate the number of unique paths from the top-left corner to the bottom-right corner of an m x n grid, where you can only move right or down. The function should start with: ```python from typing import List def unique_paths(m: int, n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def unique_paths(m: int, n: int) -> int: """ Calculate the number of unique paths from the top-left corner to the bottom-right corner of an m x n grid. Args: m (int): The number of row...
evol_instruct_66k
20,891
Write a Python function to create a 4-D matrix with random integers uniformly distributed between -1000 and 1000, and then flatten it into a 1-D array. The function should accept a list of four integers representing the dimensions of the 4-D matrix. Ensure proper error handling for invalid inputs and provide meaningful...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import numpy as np def create_and_flatten_matrix(dimensions: List[int]) -> np.ndarray: """ Creates a 4-D matrix with random integers uniformly distributed between -1000 and 1000, and then flattens it...
evol_instruct_66k
20,899
Write a Python function to compute the cumulative sum of all the elements in a given list of integers. The function should handle both positive and negative integers. The code should start with: ```python from typing import List def cumulative_sum(arr: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def cumulative_sum(arr: List[int]) -> int: """ Compute the cumulative sum of all elements in a given list of integers. Args: arr (List[int]): The list of integers for which the cumulative su...
evol_instruct_66k
20,901
Write a Python function to check if a given tuple contains any `None` values and return the indices of these `None` values. The function should be able to handle nested tuples, meaning tuples within tuples. The function should start with: ```python from typing import Tuple, List def find_none_indices(input_tuple: Tupl...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple, List def find_none_indices(input_tuple: Tuple) -> List[Tuple[int, ...]]: """ Finds and returns the indices of all `None` values in a given nested tuple. Args: input_tuple (Tuple): The tupl...
evol_instruct_66k
20,913
Write a Python function to calculate the average cost of various product types, considering both primary expenditures and auxiliary expenditures such as taxes, delivery, and insurance costs. The function should also provide the functionality to update these values and sort the items based on both individual cost and av...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Tuple def calculate_average_cost(products: Dict[str, List[Tuple[float, float]]]) -> Dict[str, float]: """ Calculate the average cost of various product types considering both primary and auxiliary...
evol_instruct_66k
20,923
Write a Python function to generate a new array where each element is the product of all elements in the input array except the one at the current index. The input array consists exclusively of integers. The function should handle cases where the input array contains zeros. The code should start with: ```python from t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def product_of_all_except_self(arr: List[int]) -> List[int]: """ Generate a new array where each element is the product of all elements in the input array except the one at the current index. Args: ...
evol_instruct_66k
20,932
Write a Python function to evaluate the occurrence frequency of a designated integer, specified as `num`, in a given list `arr`. The list `arr` should contain only integer elements. The function should return the count of occurrences of `num` in `arr`. 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 count_occurrences(arr: List[int], num: int) -> int: """ Counts the number of occurrences of a specified integer in a given list. Args: arr (List[int]): The list of integers in which to c...
evol_instruct_66k
20,951
Write a Python function to create a deep copy of a given list. The function should handle nested lists and ensure that the copied list is completely independent of the original list. The code should start with: ```python from typing import List import copy def deep_copy_list(original_list: List) -> List: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List import copy def deep_copy_list(original_list: List) -> List: """ Creates a deep copy of the given list, including all nested lists. Args: original_list (List): The list to be deep copied. ...
evol_instruct_66k
20,963
Write a Python function to convert a given English capital letter into its hexadecimal notation, then convert this hexadecimal notation into its decimal counterpart, and finally interpret this decimal value into its corresponding ASCII character. The function should return a tuple containing the hexadecimal notation, t...
Here is the Python code to solve the given problem in the markdown block: ```python def convert_letter_to_hex_decimal_ascii(letter: str) -> tuple: """ Converts a given English capital letter into its hexadecimal notation, then converts this hexadecimal notation into its decimal counterpart, and finally ...
evol_instruct_66k
20,968
Write a Python function to generate and return a list of continuous, sequential integers within a specified range, including both endpoints. The function should accept two parameters: the start integer and the end integer. The function should return a list of integers from the start integer to the end integer, inclusiv...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_sequential_integers(start: int, end: int) -> List[int]: """ Generate a list of continuous, sequential integers within a specified range, including both endpoints. Args: start (i...
evol_instruct_66k
20,977
Write a Python function to multiply two dictionaries `d1` and `d2` such that: 1. If a key in `d1` maps to a value that is a dictionary and the corresponding key in `d2` also maps to a dictionary, the function should recursively multiply these nested dictionaries. 2. If a key in `d1` maps to a value that is not a dictio...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Any def multiply_dicts(d1: Dict[Any, Any], d2: Dict[Any, Any]) -> Dict[Any, Any]: """ Multiplies two dictionaries `d1` and `d2` such that: - If both values corresponding to a key are dictionaries, t...
evol_instruct_66k
20,998
Write a Python function to invert a given string without using any pre-defined functions or extra variables. The function should reverse the string in place by swapping characters within the string. The code should start with: ```python def invert_string(input_str: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def invert_string(input_str: str) -> str: """ Inverts the given string in place without using any pre-defined functions or extra variables. Args: input_str (str): The string to be inverted. Returns: str...
evol_instruct_66k
21,013
Write a Python function to update a student's information in a dictionary. The function should take a dictionary representing a student's information and a list of tuples, where each tuple contains a key and a new value to update in the dictionary. The function should return the updated dictionary. The code should sta...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Tuple def update_student_info(student_info: Dict[str, any], updates: List[Tuple[str, any]]) -> Dict[str, any]: """ Update the student information dictionary with the provided updates. Args: ...
evol_instruct_66k
21,019
Write a Python function to count the number of occurrences of each list within a given list. The function should return a dictionary where each key is a tuple representing a flattened version of the list, and the value is the number of times that list appears in the input list. The function should handle nested lists b...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Any from collections import Counter def flatten(lst: List[Any]) -> List[Any]: """ Helper function to flatten a nested list. Args: lst (list): The list to be flattened. Returns: ...
evol_instruct_66k
21,020
Write a Python function to sort a given list of integers in descending order. The function should return the sorted list. The code should start with: ```python from typing import List def sort_descending(num_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 sort_descending(num_list: List[int]) -> List[int]: """ Sorts a given list of integers in descending order. Args: num_list (List[int]): The list of integers to be sorted. Returns: ...
evol_instruct_66k
21,042
Write a Python function to calculate the maximum profit that can be achieved by buying and selling stocks multiple times, given an array of stock prices. You are allowed to carry out an infinite number of transactions, but you must sell the stock before you can buy it again. The code should start with: ```python from t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_profit_multiple_transactions(prices: List[int]) -> int: """ Calculate the maximum profit that can be achieved by buying and selling stocks multiple times. Args: prices (List[int]): A...
evol_instruct_66k
21,046
Write a Python function to calculate the product of two numerical arguments using a recursive approach. The function should handle both positive and negative integers, as well as zero. The code should start with: ```python def recursive_multiply(a: int, b: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def recursive_multiply(a: int, b: int) -> int: """ Calculate the product of two integers using a recursive approach. Args: a (int): The first integer. b (int): The second integer. Returns: int: ...
evol_instruct_66k
21,060
Write a Python function to search for a specific keyword in a given string. If the keyword exists, replace the first instance of that keyword with a different keyword and count the total number of times the original keyword appears in the string. The function should be implemented without using Python's built-in method...
Here is the Python code to solve the given problem in the markdown block: ```python def find_and_replace(string: str, keyword: str, replacement: str) -> tuple: """ Searches for a specific keyword in a given string, replaces the first instance of the keyword with a different keyword, and counts the total num...
evol_instruct_66k
21,069
Write a Python function to find the intersection of two sets without using any built-in set functions. The function should return the intersection elements in ascending order, with no repetitions. The code should start with: ```python from typing import List def set_intersection(s1: set, s2: set) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def set_intersection(s1: set, s2: set) -> List[int]: """ Find the intersection of two sets and return the elements in ascending order without using built-in set functions. Args: s1 (set): Th...
evol_instruct_66k
21,070
Write a Python function to calculate the sum of all elements in a given list of integers. The function should handle an empty list by returning 0. The code should start with: ```python from typing import List def sum_of_list(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_list(numbers: List[int]) -> int: """ Calculate the sum of all elements in a given list of integers. Args: numbers (List[int]): The list of integers to sum. Returns: ...
evol_instruct_66k
21,074
Write a Python function to implement the Fibonacci Search algorithm for finding a particular number in a provided sorted sequence of numbers. The sequence will have 1000+ elements, include negative values, and the target number would be a negative number. The algorithm should also handle duplicate values. The code shou...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def smallest_fib_greater_equal(n: int) -> int: """ Find the smallest Fibonacci number that is greater than or equal to n. Args: n (int): The number to compare against. Returns: ...
evol_instruct_66k
21,083
Write a Python function to replace all occurrences of a specified item in a given list with a new item, while preserving the original structure of the list. The function should handle nested lists and maintain the nested structure. The code should start with: ```python from typing import List, Any def replace_item_in_...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List, Any def replace_item_in_nested_list(original_list: List[Any], old_item: Any, new_item: Any) -> List[Any]: """ Replace all occurrences of a specified item in a nested list with a new item, while preser...
evol_instruct_66k
21,095
Write a Python function to calculate the final amount after applying a discount to the initial cost of a product. The function should handle both default and custom discount rates, and it should validate the inputs to ensure they are positive numbers. The code should start with: ```python def compute_discount(cost: flo...
Here is the Python code to solve the given problem in the markdown block: ```python def compute_discount(cost: float, discount_rate: float = 0.15) -> float: """ Calculate the final amount after applying a discount to the initial cost of a product. Args: cost (float): The initial cost of the product...
evol_instruct_66k
21,106
Write a Python function to convert pressure measurements from the SI unit Pascal (Pa) to the non-SI unit Bar (bar). The conversion factor between Pascal and Bar is 1 Bar = 100,000 Pascal. The function should take a single argument representing the pressure in Pascal and return the corresponding pressure in Bar. The co...
Here is the Python code to solve the given problem in the markdown block: ```python def pascal_to_bar(pascal: float) -> float: """ Convert pressure from Pascal (Pa) to Bar (bar). Args: pascal (float): The pressure in Pascal. Returns: float: The pressure in Bar. """ # Conversion...
evol_instruct_66k
21,109
Write a Python function to convert a given string into a list of its constituent characters. The function should handle any string input, including empty strings, and return a list containing each character from the string as a separate element. The code should start with: ```python from typing import List def string...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def string_to_char_list(s: str) -> List[str]: """ Converts a given string into a list of its constituent characters. Args: s (str): The input string to be converted. Returns: Li...
evol_instruct_66k
21,134
Write a Python function to perform element-wise multiplication of two vectors of the same dimension. The vectors can have any dimension, not necessarily five. The function should return the resultant vector after multiplication. If the vectors are not of the same dimension, the function should return an error message i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def element_wise_multiplication(a: List[int], b: List[int]) -> Union[List[int], str]: """ Perform element-wise multiplication of two vectors of the same dimension. Args: a (List[int])...
evol_instruct_66k
21,135
Write a Python function to determine the number of days one must wait for a temperature increase for each day in a given sequence of daily temperatures. If no such day exists in the future, the value should be `0`. The function should start with: ```python from typing import List def daily_temperatures(temperatures: L...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def daily_temperatures(temperatures: List[int]) -> List[int]: """ Determine the number of days one must wait for a temperature increase for each day in a given sequence of daily temperatures. Args: ...
evol_instruct_66k
21,139
Write a Python function to generate the first `n` numbers in the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The function should return a list containing the first `n` Fibonacci numbers. The code should start w...
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]: """ Generates the first n numbers in the Fibonacci sequence. Args: n (int): The number of Fibonacci numbers to generate. Returns: Li...
evol_instruct_66k
21,142
Write a Python function to remove all duplicates from a given list while maintaining the original order of elements. The function should take a list of integers as input and return a new list with all duplicates removed. The code should start with: ```python from typing import List def remove_duplicates_preserve_order...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates_preserve_order(mylist: List[int]) -> List[int]: """ Removes duplicates from the given list while preserving the original order of elements. Args: mylist (List[int]): Th...
evol_instruct_66k
21,144
Write a Python function to generate `n` unique random numbers between 1 and 100, inclusive, ensuring that no number is repeated and efficiently handling potential collisions. The function should have a complexity better than O(n^2). The code should start with: ```python from typing import List import random def genera...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def generate_unique_random_numbers(n: int) -> List[int]: """ Generate n unique random numbers in the range 1-100 (both inclusive). Args: n (int): The number of unique random nu...
evol_instruct_66k
21,148
Write a Python function to implement the bubble sort algorithm on a given list of unique whole numbers. The function should sort the list in ascending order. The code should start with: ```python from typing import List def bubble_sort(sequence: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def bubble_sort(sequence: List[int]) -> List[int]: """ Sorts a list of unique whole numbers in ascending order using the bubble sort algorithm. Args: sequence (List[int]): The list of unique...
evol_instruct_66k
21,149
Write a Python function to filter out email addresses that are associated with the domain name "example.com" using a regular expression. The function should take a list of email addresses as input and return a list of email addresses that match the specified domain. 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 import re def filter_example_com_emails(emails: List[str]) -> List[str]: """ Filters out email addresses that are associated with the domain "example.com". Args: emails (List[str]): A list o...
evol_instruct_66k
21,152
Write a Python function to reverse each sub-array in a given two-dimensional array, and then reverse the entire two-dimensional array. The function should return the modified two-dimensional array. The code should start with: ```python from typing import List def reverse_2d_array(array: List[List[int]]) -> List[List[...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_2d_array(array: List[List[int]]) -> List[List[int]]: """ Reverses each sub-array in a given two-dimensional array and then reverses the entire array. Args: array (List[List[int]]...
evol_instruct_66k
21,160
Write a Python function to create a nested dictionary from two lists of tuples, where each tuple in the first list represents a key pair (main key and subkey), and each tuple in the second list represents a value pair (main value and subvalue). The function should map each key pair to the corresponding value pair in th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def create_nested_dict(keys: List[Tuple[str, str]], values: List[Tuple[str, str]]) -> Dict[str, Dict[str, Tuple[str, str]]]: """ Creates a nested dictionary from two lists of tuples. Ar...
evol_instruct_66k
21,166
Write a Python function to determine if two given strings are isomorphic. Two strings are isomorphic if there is a one-to-one mapping possible for every character of the first string to every character of the second string. The function should return `True` if the strings are isomorphic, and `False` otherwise. The cod...
Here is the Python code to solve the given problem in the markdown block: ```python def are_isomorphic(string1: str, string2: str) -> bool: """ Determines if two strings are isomorphic. Two strings are isomorphic if there is a one-to-one mapping possible for every character of the first string to every...
evol_instruct_66k
21,167
Write a Python function to identify all prime numbers within a specified list of numerical values, including nested lists. The function should return a list of prime numbers sorted in ascending order. The function should be able to handle nested lists recursively. The code should start with: ```python from typing impo...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union import math 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 ...
evol_instruct_66k
21,168
Write a Python function to check if each number within a list is within a specified range. The function should be optimized for larger inputs and have a time complexity of O(n). The function should return `True` if all numbers in the list are within the range `[lower_limit, upper_limit]`, and `False` otherwise. The co...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def within_range(lst: List[int], lower_limit: int, upper_limit: int) -> bool: """ Check if each number in the list is within the specified range [lower_limit, upper_limit]. Args: lst (List[i...
evol_instruct_66k
21,171
Write a Python function to determine if one binary string can be transformed into another by flipping exactly one bit. The function should return `True` if the transformation is possible, and `False` otherwise. The code should start with: ```python def can_transform_by_one_flip(bin_str1: str, bin_str2: str) -> bool: ``...
Here is the Python code to solve the given problem in the markdown block: ```python def can_transform_by_one_flip(bin_str1: str, bin_str2: str) -> bool: """ Determines if one binary string can be transformed into another by flipping exactly one bit. Args: bin_str1 (str): The first binary string. ...
evol_instruct_66k
21,177
Write a Python function to sort a given list of numerical figures in ascending order. The function should return the sorted list without modifying the original list. The code should start with: ```python from typing import List def sort_numbers(numbers: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_numbers(numbers: List[int]) -> List[int]: """ Sorts a given list of numerical figures in ascending order and returns the sorted list. Args: numbers (List[int]): The list of numerica...
evol_instruct_66k
21,178
Write a Python function to merge two linked lists, `list1` and `list2`, by removing nodes from `list1` starting from the `ath` node to the `bth` node, and replacing them with `list2`. The resultant linked list should be constructed and its head returned. The function should start with: ```python from typing import Opt...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Optional class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def merge_in_between_lists(list1: Optional[ListNode], a: int, b: int, list2: Optional[ListNode]) -> ...
evol_instruct_66k
21,181
Write a Python function to filter out the odd numbers from a given list of integers. The function should return a new list containing only the even numbers from the input list. The code should start with: ```python from typing import List def filter_even_numbers(numbers: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def filter_even_numbers(numbers: List[int]) -> List[int]: """ Filters out the odd numbers from the given list of integers and returns a new list containing only the even numbers. Args: num...
evol_instruct_66k
21,209
Write a Python function to invert the sequence of words in a given text string `s`. The function should handle multiple spaces between words and spaces at the beginning or end of the string. The output should be a string with the words in inverted order, joined by a single space, and should not contain any leading or t...
Here is the Python code to solve the given problem in the markdown block: ```python def invert_word_sequence(s: str) -> str: """ Inverts the sequence of words in a given text string `s`. Args: s (str): The input string containing words separated by spaces. Returns: str: A string with t...
evol_instruct_66k
21,212
Write a Python function to classify a list of CSS properties into three distinct clusters: "Layout & Spacing Properties", "Background Properties", and "Text & Font Properties". The function should take a list of CSS properties as input and return a dictionary with the classified clusters. The code should start with: `...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def classify_css_properties(css_properties: List[str]) -> Dict[str, List[str]]: """ Classify a list of CSS properties into three distinct clusters: "Layout & Spacing Properties", "Background Pr...
evol_instruct_66k
21,214
Write a Python function to compute the arithmetic mean of a list of numerical values. The function should handle lists of any length, including empty lists. If the list is empty, the function should return `None`. The code should start with: ```python from typing import List, Optional def arithmetic_mean(numbers: List...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def arithmetic_mean(numbers: List[int]) -> Optional[float]: """ Compute the arithmetic mean of a list of numerical values. Args: numbers (List[int]): A list of integers for which t...
evol_instruct_66k
21,231
Write a Python function to convert an array of integers into their corresponding strings. The function should handle both positive and negative integers, as well as zero. The function should return a list of strings where each string represents the corresponding integer from the input list. 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 convert_to_strings(lst: List[int]) -> List[str]: """ Converts an array of integers into their corresponding strings. Args: lst (List[int]): The list of integers to be converted. Ret...
evol_instruct_66k
21,243
Write a Python function to reverse the order of words in a given sentence. The function should handle sentences with varying lengths and multiple spaces between words. The code should start with: ```python def reverse_sentence(sentence: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: : ```python def reverse_sentence(sentence: str) -> str: """ Reverses the order of words in a given sentence. Args: sentence (str): The input sentence whose words are to be reversed. Returns: str: A string with th...
evol_instruct_66k
21,258
Write a Python function to extract and return the values related to a celestial body from a given map. The map contains the name of the planet, its average distance from the sun in millions of kilometers, and its orbital period in Earth years. The function should return these values as a tuple in the order: planet name...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Tuple def extract_celestial_body_info(planet_map: Dict[str, float]) -> Tuple[str, float, float]: """ Extracts and returns the values related to a celestial body from a given map. Args: plan...
evol_instruct_66k
21,266
Write a Python function to count the number of even numbers in a given list of integers. The function should efficiently iterate through the list and count the even numbers. The code should start with: ```python from typing import List def count_even_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 count_even_numbers(numbers: List[int]) -> int: """ Counts the number of even numbers in a given list of integers. Args: numbers (List[int]): A list of integers. Returns: int...
evol_instruct_66k
21,272
Write a Python function to calculate the mean of a list of integers while ensuring overflow protection. The function should handle large integers and prevent overflow by using Python's built-in capabilities for handling large numbers. The function should also handle edge cases such as an empty list. The code should st...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_mean_with_overflow_protection(arr: List[int]) -> float: """ Calculate the mean of a list of integers with overflow protection. Args: arr (List[int]): The list of integers for w...
evol_instruct_66k
21,278
Write a Python function to determine if a given string consists only of numeric characters. The function should return `True` if the string contains only digits, and `False` otherwise. The code should start with: ```python def is_numeric_string(s: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_numeric_string(s: str) -> bool: """ Determines if the given string consists only of numeric characters. Args: s (str): The string to be checked. Returns: bool: True if the string contains only di...
evol_instruct_66k
21,282
Write a Python function to sort a given array of numerical elements in descending order. The function should return the sorted array. The code should start with: ```python from typing import List def sort_array_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_array_descending(arr: List[int]) -> List[int]: """ Sorts the given array of numerical elements in descending order. Args: arr (List[int]): The array of numerical elements to be so...
evol_instruct_66k
21,286
Write a Python function to perform a mathematical operation on two numbers based on a given operator. The function should handle all possible error scenarios, including invalid input types, invalid operations, and division by zero. The function should not use the built-in `eval` function. The code should start with: `...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Union import operator def perform_operation(number1: Union[int, float], number2: Union[int, float], operation: str) -> Union[int, float, str]: """ Perform a mathematical operation on two numbers based on the ...
evol_instruct_66k
21,290
Write a Python function to count the number of unique keys in a given dictionary. The function should handle dictionaries with any type of keys and values. The code should start with: ```python from typing import Dict def count_unique_keys(dictionary: Dict) -> int: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import Dict def count_unique_keys(dictionary: Dict) -> int: """ Count the number of unique keys in a given dictionary. Args: dictionary (Dict): The dictionary from which to count the unique keys. ...
evol_instruct_66k
21,310
Write a Python function to find all missing numbers in a sorted array of non-negative integers with possible duplicates. The array is guaranteed to be in non-decreasing order. The function should efficiently handle duplicates and return a list of all missing numbers in the range from 0 to the maximum value in the array...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_missing_numbers(arr: List[int]) -> List[int]: """ Find all missing numbers in a sorted array of non-negative integers with possible duplicates. Args: arr (List[int]): A sorted list ...
evol_instruct_66k
21,314
Write a Python function to calculate the maximum sum of all unique subarrays from a given array of integers. A subarray is a contiguous part of an array. The function should return the maximum sum that can be achieved from these subarrays. The code should start with: ```python from typing import List def max_subarray...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_subarray_sum(nums: List[int]) -> int: """ Calculate the maximum sum of all unique subarrays from a given array of integers. Args: nums (List[int]): The input array of integers. ...
evol_instruct_66k
21,328
Write a Python function to flatten a given 2D matrix into a single linear list and categorize each element into either 'even' or 'odd'. The function should return a list of tuples where each tuple contains an element from the flattened list and its corresponding category ('even' or 'odd'). The code should start with: ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def flatten_and_categorize(matrix: List[List[int]]) -> List[Tuple[int, str]]: """ Flattens a given 2D matrix into a single linear list and categorizes each element into either 'even' or 'odd'. ...
evol_instruct_66k
21,341
Write a Python function to determine whether a particular element is present within a provided list using two different methods: one using a linear search and the other using Python's built-in membership operator. The function should return a tuple containing the results of both methods. The code should start with: ``...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def is_item_present(list: List[int], item: int) -> Tuple[bool, bool]: """ Determines whether a particular element is present within a provided list using two different methods. Args: ...
evol_instruct_66k
21,343
Write a Python function to find the longest common subsequence (LCS) of two given strings. The LCS is the longest sequence of characters that appear in the same order in both strings, but not necessarily consecutively. The function should return the length of the LCS. The code should start with: ```python def longest_...
Here is the Python code to solve the given problem in the markdown block: ```python def longest_common_subsequence(str1: str, str2: str) -> int: """ Calculate the length of the longest common subsequence (LCS) of two strings. Args: str1 (str): The first string. str2 (str): The second string...
evol_instruct_66k
21,345
Write a Python function to print a formatted string "X out of Y" where X is a given integer and Y is a given total number. If X is greater than Y, the function should print an error message instead. The function should start with: ```python def print_x_out_of_y(x: int, y: int) -> None: ```
Here is the Python code to solve the given problem in the markdown block: ```python def print_x_out_of_y(x: int, y: int) -> None: """ Prints a formatted string "X out of Y" if X is less than or equal to Y. If X is greater than Y, prints an error message. Args: x (int): The value of X. y...
evol_instruct_66k
21,353
Write a Python function to sort a given array in-place using the Bubble Sort algorithm. The function should modify the original array and return the sorted array. The code should start with: ```python from typing import List def sort_array_in_place(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_array_in_place(arr: List[int]) -> List[int]: """ Sorts the given array in-place using the Bubble Sort algorithm. Args: arr (List[int]): The array to be sorted. Returns: ...
evol_instruct_66k
21,356
Write a Python function to calculate the total cost of a given shopping list. Each item in the shopping list is represented as a dictionary with keys `"name"`, `"price"`, and `"qty"`. The function should sum the total cost by multiplying the price of each item by its quantity and then summing these products. The code ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def calculate_total_cost(shopping_list: List[Dict[str, int]]) -> int: """ Calculate the total cost of a given shopping list. Args: shopping_list (List[Dict[str, int]]): A list of dicti...
evol_instruct_66k
21,365
Write a Python function to generate a list of pseudo-random numbers within the interval [0, 10]. Ensure that the random number generator is seeded appropriately to produce different sequences of numbers each time the function is called. The function should accept an integer `n` as input, which specifies the number of r...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random import time def generate_random_numbers(n: int) -> List[int]: """ Generates a list of n pseudo-random numbers within the interval [0, 10]. Args: n (int): The number of random n...
evol_instruct_66k
21,399
Write a Python function to filter and return a list of all elements greater than a specified threshold from a given list of numbers. The function should be efficient and handle various edge cases, such as an empty list or a list with no elements greater than the threshold. 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 filter_elements_greater_than(numbers: List[int], threshold: int) -> List[int]: """ Filters and returns a list of all elements greater than the specified threshold from the given list of numbers. ...
evol_instruct_66k
21,418
Write a Python function to sort a list of tuples based on the second element (score) in descending order. Each tuple in the list contains a name and a score. The function should return the sorted list. The code should start with: ```python from typing import List, Tuple def sort_by_score_descending(data: List[Tuple[s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def sort_by_score_descending(data: List[Tuple[str, int]]) -> List[Tuple[str, int]]: """ Sorts a list of tuples based on the second element (score) in descending order. Args: data (Lis...
evol_instruct_66k
21,425
Write a Python function to perform a rotational displacement, akin to a circular shift, on a given list of integers. The shift should be equivalent to a specified numerical position count. The function should handle both positive and negative shift values, where a positive value indicates a right shift and a negative v...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def circular_shift(arr: List[int], k: int) -> List[int]: """ Perform a circular shift on a given list of integers. Args: arr (List[int]): The list of integers to be shifted. k (int):...
evol_instruct_66k
21,431
Write a Python function to reconstruct the original text from a list of discrete lexical elements (words) while preserving their original sequential organization. The function should join the words with a single space and return the reconstructed text. 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 reconstruct_text(words: List[str]) -> str: """ Reconstructs the original text from a list of discrete lexical elements (words). Args: words (List[str]): A list of strings representing th...
evol_instruct_66k
21,435
Write a Python function to count the occurrences of each character in a given string. The function should return a dictionary where the keys are the characters in the string and the values are the counts of those characters. The code should start with: ```python from typing import Dict def character_count(input_strin...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def character_count(input_string: str) -> Dict[str, int]: """ Counts the occurrences of each character in the given string. Args: input_string (str): The string to count characters in. ...
evol_instruct_66k
21,450
Write a Python function to calculate the variance of elements in a given list of numbers. The variance is a measure of how much the values in a dataset differ from the mean (average) value. The formula for variance is the average of the squared differences from the mean. 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 def calculate_variance(numbers: List[float]) -> float: """ Calculate the variance of a list of numbers. Variance is a measure of how much the values in a dataset differ from the mean (average) value...
evol_instruct_66k
21,455
Write a Python function to insert a new element into an existing unsorted array, ensuring that the array does not contain any duplicates and maintains the order of insertion. The function should return the modified array. The code should start with: ```python from typing import List from collections import OrderedDict...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List from collections import OrderedDict def insert_element_unique_order(arr: List[int], elem: int) -> List[int]: """ Inserts a new element into an unsorted array, ensuring the array does not contain any dupl...
evol_instruct_66k
21,456
Write a Python function to sort an array of integers using the Merge Sort algorithm. The function should recursively divide the array into halves until each subarray contains one or zero elements, and then merge the sorted subarrays back together. The code should start with: ```python from typing import List def merge...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sorts an array of integers using the Merge Sort algorithm. Args: arr (List[int]): The array of integers to be sorted. Returns: L...
evol_instruct_66k
21,458
Write a Python function to generate a response that contains a list of words sorted in increasing alphabetical order. The function should take a list of words as input and return a string where the words are joined by a comma and a space. The code should start with: ```python from typing import List def generate_sort...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_sorted_response(words: List[str]) -> str: """ Generates a response containing the words sorted in increasing alphabetical order, with each word separated by a comma and a space. Arg...
evol_instruct_66k
21,471
Write a Python function to find the numerical positions of all singleton elements in a given list of integers. A singleton element is an element that appears exactly once in the list. The function should return a list of indices where these singleton elements are located. The code should start with: ```python from typ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List from collections import Counter def find_singleton_positions(arr: List[int]) -> List[int]: """ Find the positions of all singleton elements in the given list of integers. Args: arr (List[int...
evol_instruct_66k
21,483
Write a Python function to generate a random permutation of a given list. The function should return a new list that is a shuffled version of the input list, without modifying the original list. The code should start with: ```python from typing import List import random def random_permutation(input_list: List[int]) ->...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def random_permutation(input_list: List[int]) -> List[int]: """ Generate a random permutation of the given list. Args: input_list (List[int]): The list to be permuted. Ret...
evol_instruct_66k
21,489
Write a Python function to convert a given string into its binary equivalent, where each character's binary representation is 8 bits long, and return the concatenated binary string. The function should not print the result but return it as a string. The code should start with: ```python def string_to_binary(s: str) -> ...
Here is the Python code to solve the given problem in the markdown block: ```python def string_to_binary(s: str) -> str: """ Converts a given string into its binary equivalent, where each character's binary representation is 8 bits long. Args: s (str): The input string to be converted into binary. ...
evol_instruct_66k
21,491
Write a Python function to generate the first `n` elements of the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The function should return a list containing the first `n` Fibonacci numbers. The code should start ...
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 elements of the Fibonacci sequence. The Fibonacci sequence is a series of numbers where each number is the sum of the two preced...
evol_instruct_66k
21,495
Write a Python function to generate a Fibonacci sequence of a specified length `n` efficiently. The function should return a list containing the first `n` Fibonacci numbers. The code should start with: ```python from typing import List def generate_fibonacci_sequence(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_sequence(n: int) -> List[int]: """ Generate a Fibonacci sequence of length `n`. Args: n (int): The length of the Fibonacci sequence to generate. Returns: ...
evol_instruct_66k
21,519
Write a Python function to recursively invert the sequence of elements within a provided numerical array. The function should ensure that it does not consume more than O(log N) extra space. The code should start with: ```python from typing import List def recursive_reverse(arr: List[int], start: int, end: int) -> None...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def recursive_reverse(arr: List[int], start: int, end: int) -> None: """ Recursively reverses the elements of the provided array in place. Args: arr (List[int]): The array to be reversed. ...
evol_instruct_66k
21,525
Write a Python function to determine the frequency of each digit in a given number, identify the digit with the highest and lowest frequency, and return these results as a dictionary and two integers. If two digits have the same frequency, the function should return the smallest digit. The function should be optimized ...
Here is the Python code to solve the given problem in the markdown block: ```python from collections import defaultdict def digit_frequency(n: int) -> tuple: """ Determine the frequency of each digit in a given number, identify the digit with the highest and lowest frequency, and return these results as a ...
evol_instruct_66k
21,555
Write a Python function to find the position of the first character that differs between two given strings. If the strings are identical, return -1. If the strings are of different lengths and identical up to the length of the shorter string, return the length of the shorter string. The code should start with: ```pyth...
Here is the Python code to solve the given problem in the markdown block: ```python def find_first_difference_position(s1: str, s2: str) -> int: """ Find the position of the first character that differs between two given strings. Args: s1 (str): The first string to compare. s2 (str): The se...
evol_instruct_66k
21,557
Write a Python function to remove the last `n` elements from a given list. The function should handle invalid inputs and edge cases by raising appropriate exceptions. Specifically, the function should: 1. Raise a `ValueError` if the first argument is not a list. 2. Raise a `ValueError` if the second argument `n` is not...
Here is the Python code to solve the given problem in the markdown block: ```python def remove_last_n_elements(lst, n): """ Removes the last n elements from the given list and returns a new list. Args: lst (list): The list from which to remove elements. n (int): The number of elements to re...
evol_instruct_66k
21,566
Write a Python function to construct a dictionary where each key is a letter from the English alphabet (a-z) and the corresponding value is an integer ranging from 1 to 26. The function should handle the construction in multiple steps, ensuring clarity and correctness. The code should start with: ```python def constru...
Here is the Python code to solve the given problem in the markdown block: ```python def construct_alphabet_dict() -> dict: """ Constructs a dictionary where each key is a letter from the English alphabet (a-z) and the corresponding value is an integer ranging from 1 to 26. Returns: dict: A dict...
evol_instruct_66k
21,573
Write a Python function to search and substitute all the email addresses with the term "EMAIL" in a provided text using regular expressions. The function should be robust enough to handle various email formats and should return the modified text. The code should start with: ```python import re def replace_emails(text...
Here is the Python code to solve the given problem in the markdown block: ```python import re def replace_emails(text: str) -> str: """ Replaces all email addresses in the provided text with the term "EMAIL". Args: text (str): The input text in which to search and replace email addresses. Ret...
evol_instruct_66k
21,577
Create a Python function that takes a list of ocean names and returns a dictionary with the ocean names as keys and their corresponding depths in meters as values. If an ocean name is not found in the predefined list of the world's deepest oceans, its depth should be set to `None`. 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, Dict # Predefined dictionary of the world's deepest oceans and their depths oceans_depth = { 'Pacific Ocean': 10911, 'Atlantic Ocean': 8486, 'Indian Ocean': 7906, 'Southern Ocean': 7235, ...
evol_instruct_66k
21,578
Write a Python function to determine if there exists a pair of numbers in a given list that sum up to a specified target number. The function should return `True` if such a pair exists, otherwise `False`. The code should start with: ```python from typing import List def has_pair_with_sum(numbers: List[int], target: in...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def has_pair_with_sum(numbers: List[int], target: int) -> bool: """ Determines if there exists any pair of numbers in the given list that sum up to the specified target. Args: numbers (List[...
evol_instruct_66k
21,580
Write a Python function to generate and return the Pascal's Triangle up to the nth level as a list of lists. Each inner list represents a row in the Pascal's Triangle. The function should handle the case where n is 0 by returning an empty list. The code should start with: ```python from typing import List def generat...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_pascals_triangle(n: int) -> List[List[int]]: """ Generate Pascal's Triangle up to the nth level. Args: n (int): The number of levels to generate. Returns: List[List...