source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
magic_evol_110k
86,733
Write a Python function to perform element-wise addition, subtraction, and multiplication on two 5-dimensional arrays of the same dimensions. The function should return a tuple containing the results of these operations in the order of addition, subtraction, and multiplication. The code should start with: ```python imp...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np from typing import Tuple def perform_operations_on_5d_arrays(array1: np.ndarray, array2: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """ Perform element-wise addition, subtraction, and multiplic...
magic_evol_110k
86,744
Write a Python function to remove duplicate elements from a given list while preserving the order of the unique elements. The function should have the minimum time and memory complexity. The code should start with: ```python from typing import List def remove_duplicates(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 remove_duplicates(input_list: List[int]) -> List[int]: """ Removes duplicate elements from the given list while preserving the order of the unique elements. Args: input_list (List[int]):...
magic_evol_110k
86,752
Write a Python function to calculate the greatest common divisor (GCD) of two integers using the Euclidean algorithm. The function should be efficient and handle both positive and negative integers. The code should start with: ```python def gcd_euclidean(a: int, b: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def gcd_euclidean(a: int, b: int) -> int: """ Calculate the greatest common divisor (GCD) of two integers using the Euclidean algorithm. Args: a (int): The first integer. b (int): The second integer. Re...
magic_evol_110k
86,776
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 largest one. The code should start with: ```python def find_max_of_three(a: int, b: int, c: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def find_max_of_three(a: int, b: int, c: int) -> int: """ Find the maximum value among three given integers without using the built-in max function. Args: a (int): The first integer. b (int): The second inte...
magic_evol_110k
86,787
Write a Python function to determine if a given positive integer is a power of four. The function should not use any built-in mathematical functions or operators, and it should optimize for time complexity. The function should start with: ```python def is_power_of_four(n: int) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python def is_power_of_four(n: int) -> bool: """ Determine if a given positive integer is a power of four. Args: n (int): The positive integer to check. Returns: bool: True if n is a power of four, False other...
magic_evol_110k
86,795
Write a Python function to validate if an array `arr` can be constructed by concatenating the arrays in `pieces` in any sequence without reordering the integers in each individual array `pieces[i]`. Additionally, keep track of the number of concatenations made and return it along with the boolean result. If `arr` canno...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def validate_array_construction(arr: List[int], pieces: List[List[int]]) -> Tuple[bool, int]: """ Validates if the array `arr` can be constructed by concatenating the arrays in `pieces` in any seq...
magic_evol_110k
86,796
Write a Python function to convert a date string to a `datetime` object. The function should handle two possible date formats: `"%m/%d/%Y %H:%M:%S"` and `"%d/%m/%Y %H:%M:%S"`. If the date string does not match either format, the function should return `None`. The code should start with: ```python import datetime def ...
Here is the Python code to solve the given problem in the markdown block: ```python import datetime def convert_date_string(date_string: str) -> datetime.datetime: """ Converts a date string to a datetime object. The function handles two possible date formats: "%m/%d/%Y %H:%M:%S" (month/day/year) and "%d/%...
magic_evol_110k
86,803
Write a Python function to count the frequency of each character in a given string and return the result as a dictionary where the keys are the characters and the values are their respective counts. The function should be efficient and handle any non-empty string input. 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 character_frequency(mystring: str) -> Dict[str, int]: """ Counts the frequency of each character in the given string and returns a dictionary with characters as keys and their counts as values. ...
magic_evol_110k
86,813
Write a Python function to find the second largest number in a given list of integers. The function should handle edge cases such as an empty list or a list with only one element. The code should start with: ```python from typing import List def find_second_largest(numbers: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_second_largest(numbers: List[int]) -> int: """ Find the second largest number in a given list of integers. Args: numbers (List[int]): The list of integers from which to find the sec...
magic_evol_110k
86,817
Write a Python function to multiply all the elements of a given array. If the result is positive, print the result. If the result is negative, print the absolute value of the result. Additionally, return the count of negative numbers in the array. The code should start with: ```python from typing import List def mult...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def multiply_elements_and_count_negatives(arr: List[int]) -> int: """ Multiplies all the elements of a given array. If the result is positive, prints the result. If the result is negative, prints the...
magic_evol_110k
86,819
Write a Python function to replace all occurrences of a specified element in a given list with a replacement element. The function should handle lists containing any type of elements, including integers, strings, and other data types. The function should return a new list with the replacements made, leaving the origina...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def substitute_entity(array: List[Any], target: Any, replacement: Any) -> List[Any]: """ Replaces all occurrences of a specified element in a list with a replacement element. Args: arra...
magic_evol_110k
86,822
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...
magic_evol_110k
86,835
Write a Python function that constructs a lambda function to perform a mathematical operation on a given input. The lambda function should take a numeric input and return the result of the operation. Specifically, the lambda function should be designed to multiply the input by a specified factor. The function should al...
Here is the Python code to solve the given problem in the markdown block: ```python def create_multiplier(factor: float) -> callable: """ Creates a lambda function that multiplies a numeric input by the specified factor. Args: factor (float): The factor by which the input will be multiplied. R...
magic_evol_110k
86,837
Write a Python function to transform a given string by converting all uppercase characters into lowercase. The function should handle strings of varying lengths and content, including strings with no uppercase characters. The code should start with: ```python def transform_to_lowercase(input_string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def transform_to_lowercase(input_string: str) -> str: """ Transforms the given string by converting all uppercase characters into lowercase. Args: input_string (str): The string to be transformed. Returns: ...
magic_evol_110k
86,845
Write a Python function to extract and return all unique numerical elements from two given alphanumeric strings. The function should combine the two strings, identify all numerical characters, and return them as a sorted list of unique numerical elements. The code should start with: ```python from typing import List ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def extract_unique_numerical_elements(string1: str, string2: str) -> List[str]: """ Extracts and returns all unique numerical elements from two given alphanumeric strings. Args: string1 (str...
magic_evol_110k
86,848
Write a Python function to remove a specified key-value pair from a given dictionary. The function should handle cases where the key does not exist in the dictionary without raising an error. The code should start with: ```python from typing import Dict, Any def remove_key_from_dict(dictionary: Dict[Any, Any], key_to_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Any def remove_key_from_dict(dictionary: Dict[Any, Any], key_to_remove: Any) -> Dict[Any, Any]: """ Removes a specified key-value pair from the given dictionary. Args: dictionary (Dict[Any,...
magic_evol_110k
86,861
Write a Python function to perform exponentiation of an n x n matrix by a given power using the matrix multiplication method. The function should handle the case where the power is 0 by returning the identity matrix of size n x n. The function should also handle negative powers by raising the inverse of the matrix to t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def matrix_multiplication(A: List[List[int]], B: List[List[int]], n: int) -> List[List[int]]: """ Multiplies two n x n matrices A and B. Args: A (List[List[int]]): The first matrix. ...
magic_evol_110k
86,872
Write a Python function that extracts a specified number of characters from the beginning of a given string. If the specified number exceeds the length of the string, the function should return the entire string. The function should be named `extract_characters` and should accept two parameters: a string and an integer...
Here is the Python code to solve the given problem in the markdown block: ```python def extract_characters(string: str, num: int) -> str: """ Extracts the specified number of characters from the beginning of the given string. If the specified number exceeds the length of the string, returns the entire strin...
magic_evol_110k
86,875
Write a Python function to convert a binary number, represented as a string, into its corresponding decimal (base 10) value. The function should handle binary strings of any length and should be efficient. The code should start with: ```python def binary_to_decimal(binary_str: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def binary_to_decimal(binary_str: str) -> int: """ Converts a binary number, represented as a string, to its corresponding decimal (base 10) value. Args: binary_str (str): The binary number as a string (e.g., "1101"...
magic_evol_110k
86,876
Write a Python function to interlace two strings by selecting and interleaving alternate characters from each string. If one string is longer than the other, append the remaining characters of the longer string to the result. The function should start with: ```python def interlace_strings(str1: str, str2: str) -> str: ...
Here is the Python code to solve the given problem in the markdown block: ```python def interlace_strings(str1: str, str2: str) -> str: """ Interleaves two strings by selecting and interleaving alternate characters from each string. If one string is longer than the other, append the remaining characters of ...
magic_evol_110k
86,881
Write a Python function to generate a list of tuples, where each tuple contains consecutive elements from a given list. The function should handle lists of various lengths, including empty lists. The code should start with: ```python from typing import List, Tuple def get_consecutive_pairs(input_list: List[int]) -> Li...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def get_consecutive_pairs(input_list: List[int]) -> List[Tuple[int, int]]: """ Generates a list of tuples where each tuple contains consecutive elements from the input list. Args: inp...
magic_evol_110k
86,901
Write a Python function to determine if all elements in one array are strictly less than their corresponding elements in another array. The function should return `True` if all elements in the first array are strictly less than their corresponding elements in the second array, and `False` otherwise. The code should sta...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def are_all_elements_inferior(array1: List[int], array2: List[int]) -> bool: """ Determines if all elements in the first array are strictly less than their corresponding elements in the second array. ...
magic_evol_110k
86,903
Write a Python function to organize two distinct compilations, one constituted of numeric integers and the other of distinct English language words. The numeric compilation should be portrayed in a sequentially increasing mode, whereas the English language words compilation should be sequenced in lexicographical order....
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def organize_compilations(numeric_compilation: List[int], word_compilation: List[str]) -> Tuple[List[int], List[str]]: """ Organizes two distinct compilations: one of numeric integers and the othe...
magic_evol_110k
86,912
Write a Python function to transform a given string into its equivalent representation in lowercase characters. The function should handle any string input, including those with special characters and numbers, and should return the lowercase version of the input string. The code should start with: ```python def transf...
Here is the Python code to solve the given problem in the markdown block: ```python def transform_to_lowercase(input_str: str) -> str: """ Transforms the given string into its equivalent representation in lowercase characters. Args: input_str (str): The input string to be transformed. Returns:...
magic_evol_110k
86,914
Write a Python function to find the k-th smallest number in a list of integers without sorting the entire list. The function should have a time complexity no worse than O(n). The code should start with: ```python from typing import List def find_kth_smallest(lst: List[int], k: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_kth_smallest(lst: List[int], k: int) -> int: """ Finds the k-th smallest number in a list of integers without sorting the entire list. Args: lst (List[int]): The list of integers fr...
magic_evol_110k
86,936
Write a Python function to rearrange a given array in maximum-minimum form. The rearranged array should start with the maximum element, followed by the minimum element, then the second maximum, followed by the second minimum, and so on. The code should start with: ```python from typing import List def rearrange_max_mi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def rearrange_max_min(arr: List[int]) -> List[int]: """ Rearranges the given array in maximum-minimum form. Args: arr (List[int]): The input array to be rearranged. Returns: Lis...
magic_evol_110k
86,943
Write a Python function to calculate the total sum of all integer values present within nested lists. The function should ignore any non-integer values and continue processing the rest of the list. The code should start with: ```python from typing import List, Union def sum_nested_list(nested_list: List[Union[int, Lis...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def sum_nested_list(nested_list: List[Union[int, List]]) -> int: """ Calculate the total sum of all integer values present within nested lists, ignoring non-integer values. Args: nest...
magic_evol_110k
86,961
Write a Python function to create a deep copy of a given list of integers. A deep copy means that the new list will have the same elements as the original list, but any modifications to the new list will not affect the original list. The function should use a for loop to achieve this. The code should start with: ```py...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def deep_copy_list(arr: List[int]) -> List[int]: """ Creates a deep copy of a given list of integers. Args: arr (List[int]): The original list of integers to be copied. Returns: ...
magic_evol_110k
86,965
Write a Python function to encode and decode a given input string using the ROT13 substitution cipher method. The function should handle both alphabetic characters (both uppercase and lowercase) and numeric characters. Special characters should remain unchanged. The function should be able to encode and decode the stri...
Here is the Python code to solve the given problem in the markdown block: ```python def rot13(text: str) -> str: """ Encodes or decodes the given input string using the ROT13 substitution cipher. This function handles both alphabetic characters (uppercase and lowercase) and numeric characters. Special c...
magic_evol_110k
86,975
Write a Python function to calculate the product of the digits of a given number. The function should handle both positive and negative integers. If the number is negative, the function should ignore the negative sign and calculate the product of the digits. The function should return the product as an integer. The co...
Here is the Python code to solve the given problem in the markdown block: ```python def product_of_digits(n: int) -> int: """ Calculate the product of the digits of a given number. Args: n (int): The number whose digits' product is to be calculated. Returns: int: The product of the dig...
magic_evol_110k
86,984
Write a Python function to generate and print the Fibonacci sequence up to a given number of terms `n`. The function should correctly handle edge cases such as `n` being 0 or 1. The code should start with: ```python def print_fibonacci_sequence(n: int): ```
Here is the Python code to solve the given problem in the markdown block: ```python def print_fibonacci_sequence(n: int): """ Generates and prints the Fibonacci sequence up to a given number of terms. Args: n (int): The number of terms in the Fibonacci sequence to generate. Returns: No...
magic_evol_110k
86,988
Write a Python function that returns the product of the two smallest integers in a given list of unique positive integers. The function should handle erroneous inputs effectively, including checking for the correct input type, ensuring the list has at least two elements, verifying that all elements are integers, and en...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def product_of_smallest_numbers(numbers_list: List[int]) -> int or str: """ Returns the product of the two smallest integers in a given list of unique positive integers. Args: numbers_list (...
magic_evol_110k
86,995
Write a Python function to remove all punctuation marks from a given input string and return the cleaned string. The function should handle various punctuation marks such as commas, periods, exclamation marks, question marks, colons, semicolons, and apostrophes. The code should start with: ```python import string def ...
Here is the Python code to solve the given problem in the markdown block: ```python import string def remove_punctuation(input_string: str) -> str: """ Removes all punctuation marks from the given input string. Args: input_string (str): The input string from which punctuation marks are to be remov...
magic_evol_110k
87,004
Write a Python function to detect and replace an outlier number in a sequence, and calculate the total changes made. The sequence is an integer series from 1 to `m` (inclusive) with no repetitions and one outlier. The function should return a dictionary containing the index of the outlier, the index of the next best re...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def fix_outlier(seq: List[int], m: int) -> Dict[str, int]: """ Detects and replaces an outlier number in a sequence and calculates the total changes made. Args: seq (List[int]): The se...
magic_evol_110k
87,010
Write a Python function to construct a linked list from a given list of integers, where each integer represents a node's data element. The function should also provide a method to print the linked list. The linked list should be constructed such that each node contains the data and a reference to the next node. The co...
Here is the Python code to solve the given problem in the markdown block: ```python class Node: def __init__(self, data): self.data = data self.next = None def construct_linked_list(data_list: list) -> Node: """ Constructs a linked list from a given list of integers. Args: data...
magic_evol_110k
87,012
Write a Python function to transpose a given square matrix in-place. The function should not allocate additional memory for the result. The matrix is guaranteed to be a square matrix (m == n). The code should start with: ```python from typing import List def transpose_matrix(matrix: List[List[int]]) -> None: ```
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]]) -> None: """ Transposes a given square matrix in-place. Args: matrix (List[List[int]]): The square matrix to be transposed. Returns: ...
magic_evol_110k
87,015
Write a Python function to determine if a given number is a perfect square. A perfect square is a number that can be expressed as the square of an integer. The function should handle both positive and negative integers. If the input number is negative, the function should return `False` since negative numbers cannot be...
Here is the Python code to solve the given problem in the markdown block: ```python import math def is_perfect_square(n: int) -> bool: """ Determine if a given number is a perfect square. Args: n (int): The number to check. Returns: bool: True if the number is a perfect square, False ...
magic_evol_110k
87,020
Write a Python function to iterate over a given list in reverse order and return a new list containing the elements in the reversed 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(numbers: List[int]) -> List[in...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_list(numbers: List[int]) -> List[int]: """ Reverses the order of elements in the given list and returns a new list with the elements in reverse order. Args: numbers (List[int]): ...
magic_evol_110k
87,022
Write a Python function to convert a list of temperature measurements from degrees Celsius to degrees Fahrenheit. The function should handle non-numeric inputs gracefully by skipping them and printing an error message. The function should start with: ```python from typing import List def convert_temperatures(celsius_l...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def convert_temperatures(celsius_list: List[float]) -> List[float]: """ Converts a list of temperature measurements from degrees Celsius to degrees Fahrenheit. Non-numeric inputs are skipped and an e...
magic_evol_110k
87,036
Write a Python function to sort a dictionary by its values in ascending order. The function should handle dictionaries with both positive and negative values, as well as recognize and handle cases with duplicate values. The function should be optimized to handle large dictionaries efficiently. The code should start wi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def sort_dict_by_value(input_dict: Dict[str, int]) -> Dict[str, int]: """ Sorts a dictionary by its values in ascending order. Handles dictionaries with both positive and negative values, as well as ...
magic_evol_110k
87,046
Write a Python function to generate a list of numbers ranging from 1 to a given upper limit `n` (inclusive) that are divisible by a specified divisor `d` without leaving any remainder. The function should return a list of these numbers. The code should start with: ```python from typing import List def generate_divisi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_divisible_numbers(n: int, d: int) -> List[int]: """ Generate a list of numbers ranging from 1 to n (inclusive) that are divisible by d without leaving any remainder. Args: n (in...
magic_evol_110k
87,053
Write a Python function to detect the occurrence of a negative whole number within a given sequence of numerical entities. The function should return `True` if there is at least one negative whole number in the sequence, and `False` otherwise. The sequence is represented as a list of numbers. The code should start wit...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def has_negative_whole_number(numbers: List[float]) -> bool: """ Detects the occurrence of a negative whole number within a given sequence of numerical entities. Args: numbers (List[float]):...
magic_evol_110k
87,055
Write a Python function to transform an array of alphabetic symbols into a concatenated textual representation. The function should handle both uppercase and lowercase letters and return the concatenated string. The code should start with: ```python from typing import List def transform_array_to_text(input_array: List...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def transform_array_to_text(input_array: List[str]) -> str: """ Transforms an array of alphabetic symbols into a concatenated textual representation. Args: input_array (List[str]): A list ...
magic_evol_110k
87,081
Write a Python function to display the elements of a given list in a specific format. The function should take a list of strings as input and print each element followed by a colon and its length. The function should start with: ```python from typing import List def display_elements_with_length(elements: List[str]) ->...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def display_elements_with_length(elements: List[str]) -> None: """ Displays each element of the given list followed by a colon and its length. Args: elements (List[str]): A list of strings w...
magic_evol_110k
87,082
Write a Python function to remove the last element from a given list and return the modified list. The function should use the `pop()` method to achieve this. The code should start with: ```python from typing import List def remove_last_element(lst: List) -> List: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_last_element(lst: List) -> List: """ Removes the last element from the given list and returns the modified list. Args: lst (List): The list from which the last element is to be re...
magic_evol_110k
87,110
Write a Python function to determine if two given strings are anagrams of each other, considering the following requirements: 1. The function should handle strings that include numbers, special characters, and a mix of lowercase and uppercase letters. 2. The function should be case-insensitive and should ignore spaces....
Here is the Python code to solve the given problem in the markdown block: ```python def are_anagrams(str1: str, str2: str) -> bool: """ Determine if two given strings are anagrams of each other. The function is case-insensitive and ignores spaces. It handles strings that include numbers, special characters...
magic_evol_110k
87,117
Write a Python function to calculate the number of weeks in a given month, considering that a week consists of 7 days. The function should take the total number of days in the month as input and return the number of weeks. The code should start with: ```python def calculate_weeks_in_month(days_in_month: int) -> float: ...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_weeks_in_month(days_in_month: int) -> float: """ Calculate the number of weeks in a given month based on the total number of days in the month. Args: days_in_month (int): The total number of days in th...
magic_evol_110k
87,123
Write a Python function to find the employee with the highest salary from a list of dictionaries representing employee records. Additionally, the function should return the count of employees with that highest salary and the average salary of all employees. Each employee record contains the following fields: 'id', 'nam...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union, Tuple def highest_salary(data: List[Dict[str, Union[int, str]]]) -> Tuple[Dict[str, Union[int, str]], int, float]: """ Finds the employee with the highest salary, the count of employees wit...
magic_evol_110k
87,125
Write a Python function to transform a given multi-dimensional list of numerical values into a structured NumPy array, and provide functionality for reshaping, sorting, and filtering the array. The function should accept the multi-dimensional list and optional parameters for reshaping, sorting, and filtering. The funct...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np from typing import List, Optional, Union def transform_array(data: List[List[int]], reshape: Optional[Union[List[int], None]] = None, sort: bool = False, filter_value: Optional[int] = None) -> np.ndarray: """ ...
magic_evol_110k
87,140
Write a Python function to perform a binary search on a sorted list of numbers to find all occurrences of a given element. If the element is found, return a list of all indices where the element appears. If the element is not found, return an empty list. The function should be optimized for time complexity. The code s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_all_occurrences(arr: List[int], x: int) -> List[int]: """ Perform a binary search to find all occurrences of a given element in a sorted list. Args: arr (List[int]): A sorted list o...
magic_evol_110k
87,141
Write a Python function to flatten a nested list of arbitrary depth into a single-dimensional list. The function should handle lists that contain other lists, which may themselves contain other lists, and so on. The goal is to convert this deeply nested structure into a flat list containing all the elements in a single...
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 nested list of arbitrary depth into a single-dimensional list. Args: nested_list (List[Any]): The nested list to be...
magic_evol_110k
87,148
Write a Python function to calculate the sum of two integers provided as command-line arguments. The function should handle the input validation to ensure that exactly two integers are provided and that they are valid integers. The function should then print the sum of these two integers. The code should start with: `...
Here is the Python code to solve the given problem in the markdown block: ```python import sys def sum_two_integers(): """ Calculate the sum of two integers provided as command-line arguments. This function reads two integers from the command line, validates them, and prints their sum. If the input is...
magic_evol_110k
87,158
Write a Python function to find and return the string with the greatest length from a given list of strings. The function should handle cases where the input list is empty by returning `None`. The code should start with: ```python from typing import List, Optional def find_longest_string(strings: List[str]) -> Optiona...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def find_longest_string(strings: List[str]) -> Optional[str]: """ Finds and returns the string with the greatest length from a given list of strings. Args: strings (List[str]): A l...
magic_evol_110k
87,165
Write a Python function to reverse the order of words in a given sentence. The function should take a string as input and return a new string with the words in reverse order. The function should handle sentences with varying lengths, including empty sentences and sentences with multiple spaces between words. The code ...
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_words_in_sentence(sentence: str) -> str: """ Reverses the order of words in a given sentence. Args: sentence (str): The input sentence to be processed. Returns: str: A new string with the wo...
magic_evol_110k
87,174
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...
magic_evol_110k
87,184
Write a Python function to process a collection of programming language names and output solely the ones containing an even count of characters. For each programming language name with an even number of characters, the function should also find and print out the count of each individual character in the name. The solut...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def process_programming_languages(word_list: List[str]) -> None: """ Processes a collection of programming language names and outputs the ones with an even count of characters. For each programming l...
magic_evol_110k
87,194
Write a Python function to count the number of words in a given string. The function should handle various edge cases, such as strings with multiple spaces, punctuation, and empty strings. The code should start with: ```python def count_words(s: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def count_words(s: str) -> int: """ Count the number of words in a given string. Args: s (str): The input string to count words from. Returns: int: The number of words in the string. """ # Strip...
magic_evol_110k
87,202
Write a Python function to encrypt a given text using the Caesar Cipher technique. The Caesar Cipher is a simple substitution cipher where each letter in the plaintext is shifted a certain number of places down or up the alphabet. The function should handle both uppercase and lowercase letters and leave non-alphabetic ...
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 the given text using the Caesar Cipher technique. Args: text (str): The text to be encrypted. shift (int): The number of positions to shi...
magic_evol_110k
87,215
Write a Python function to convert every character within a given text string into its lowercase equivalent. The function should handle any input string and return the lowercase version of the input string. The code should start with: ```python def to_lowercase(input_string: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def to_lowercase(input_string: str) -> str: """ Converts every character within a given text string into its lowercase equivalent. Args: input_string (str): The input string to be converted to lowercase. Return...
magic_evol_110k
87,220
Write a Python function to produce a resultant list where each element from the provided input sequence has been magnified by a specified factor. The function should accept a list of integers and an integer factor as input and return a new list with each element multiplied by the factor. 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 magnify_elements(input_sequence: List[int], factor: int) -> List[int]: """ Produces a resultant list where each element from the provided input sequence has been magnified by the specified factor...
magic_evol_110k
87,225
Write a Python function to determine the shared characters between two given strings, ignoring case, and count the number of occurrences of each shared character. The function should handle special characters and numbers. The code should start with: ```python from typing import Dict def shared_chars_count(str1: str, s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def shared_chars_count(str1: str, str2: str) -> Dict[str, int]: """ Determines the shared characters between two given strings, ignoring case, and counts the number of occurrences of each shared characte...
magic_evol_110k
87,233
Write a Python function to sort a given list of integers in descending order and return the sorted list. The function should be efficient and handle various edge cases, such as an empty list or a list with duplicate elements. The code should start with: ```python from typing import List def sort_descending(lst: List[i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_descending(lst: List[int]) -> List[int]: """ Sorts a given list of integers in descending order and returns the sorted list. Args: lst (List[int]): The list of integers to be sorted...
magic_evol_110k
87,236
Write a Python function to calculate the weighted median of a list of floating-point numbers given a corresponding list of weights. The function should handle invalid weights appropriately. The code should start with: ```python from typing import List def weighted_median(numbers: List[float], weights: List[float]) ->...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def weighted_median(numbers: List[float], weights: List[float]) -> float: """ Calculate the weighted median of a list of floating-point numbers given a corresponding list of weights. Args: n...
magic_evol_110k
87,240
Write a Python function to find the next smallest element in a given list of integers. The function should return `None` if the list has fewer than two elements or if there is no next smallest element. The code should start with: ```python from typing import List, Optional def next_smallest_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 next_smallest_element(lst: List[int]) -> Optional[int]: """ Find the next smallest element in a given list of integers. Args: lst (List[int]): The list of integers from which t...
magic_evol_110k
87,244
Write a Python function to invert a character sequence while maintaining case sensitivity. The character sequence is provided as a list of characters. The function should reverse the order of characters in the list while preserving the case of each character. The function must modify the input list in-place with `O(1)`...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def invert_character_sequence(s: List[str]) -> None: """ Inverts the character sequence in the given list while maintaining case sensitivity. The function modifies the input list in-place with O(1) e...
magic_evol_110k
87,265
Write a Python function to split a given string into a list of characters, excluding any numbers and special characters. The function should only include alphabetic characters (both uppercase and lowercase) in the resulting list. The code should start with: ```python from typing import List def split_string_to_chars(i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def split_string_to_chars(input_string: str) -> List[str]: """ Splits a given string into a list of characters, excluding any numbers and special characters. Args: input_string (str): The st...
magic_evol_110k
87,266
Write a Python function to rearrange the elements in a given list in-place such that all even numbers precede all odd numbers. Additionally, the even numbers should be sorted in descending order, and the odd numbers should be sorted in ascending order. The function should be efficient in terms of time complexity. The ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def rearrange_even_odd(arr: List[int]) -> None: """ Rearranges the elements in the given list in-place such that all even numbers precede all odd numbers. The even numbers are sorted in descending or...
magic_evol_110k
87,281
Write a Python function to create a dictionary from two tuples of equal length. The first tuple contains keys, and the second tuple contains corresponding values. The function should handle cases where the tuples are not of equal length by truncating the longer tuple to match the length of the shorter one. The code sh...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple, Dict def create_dictionary_from_tuples(tuple1: Tuple[str], tuple2: Tuple[str]) -> Dict[str, str]: """ Creates a dictionary from two tuples of equal length. The first tuple contains keys, and the second...
magic_evol_110k
87,308
Write a Python function to replace keys enclosed in curly braces within a given string with their corresponding values from a provided dictionary. If a key does not exist in the dictionary, it should remain unchanged in the final string. The function should maintain an average time complexity of O(n), where n is the le...
Here is the Python code to solve the given problem in the markdown block: ```python def replace_keys_with_values(string: str, dictionary: dict) -> str: """ Replaces keys enclosed in curly braces within a given string with their corresponding values from a dictionary. Args: string (str): The inp...
magic_evol_110k
87,324
Write a Python function to find an index mapping `P` from array `A` to array `B`, where `B` is an anagram of `A`. The mapping should minimize the sum of the indices in `P`. If there are multiple mappings with the same minimum sum, return any of them. The function should start with: ```python from typing import List de...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_anagram_mapping(A: List[int], B: List[int]) -> List[int]: """ Finds an index mapping `P` from array `A` to array `B` that minimizes the sum of the indices in `P`. Args: A (List[int]...
magic_evol_110k
87,335
Write a Python function to generate the Fibonacci sequence up to the nth term and another function to check if a given number exists within the generated sequence. The code should start with: ```python from typing import List, Union def generate_fibonacci(n: int) -> List[int]: """ Generate the Fibonacci sequen...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def generate_fibonacci(n: int) -> List[int]: """ Generate the Fibonacci sequence up to the nth term. Args: n (int): The number of terms in the Fibonacci sequence to generate. Ret...
magic_evol_110k
87,352
Write a Python function to reverse a given tuple and ensure that the tuple contains elements of different data types. The function should return the reversed tuple. Additionally, provide a tuple `y` that contains elements of different data types and use the function to reverse it. The code should start with: ```python...
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_tuple(t: tuple) -> tuple: """ Reverse the given tuple and return the reversed tuple. Args: t (tuple): The tuple to be reversed. Returns: tuple: The reversed tuple. """ return t[::-1]...
magic_evol_110k
87,356
Write a Python function to perform a subtraction operation between two integers. The function should take two integer parameters and return the result of subtracting the second integer from the first integer. The function should handle both positive and negative integers. The code should start with: ```python def subt...
Here is the Python code to solve the given problem in the markdown block: ```python def subtract_integers(num1: int, num2: int) -> int: """ Subtracts the second integer from the first integer and returns the result. Args: num1 (int): The first integer. num2 (int): The second integer to be s...
magic_evol_110k
87,367
Write a Python function to encrypt a given string using the Caesar Cipher technique. The Caesar Cipher involves shifting each letter in the input string by a specified number of positions in the alphabet. Non-alphabet characters should remain unchanged. The function should handle both uppercase and lowercase letters an...
Here is the Python code to solve the given problem in the markdown block: ```python def caesar_cipher(input_string: str, shift_amount: int = 3) -> str: """ Encrypts a given string using the Caesar Cipher technique. Args: input_string (str): The string to be encrypted. shift_amount (int): Th...
magic_evol_110k
87,376
Write a Python function to verify if a given array is sorted in ascending order. The function should return `True` if the array is sorted, and `False` otherwise. The code should start with: ```python from typing import List def is_sorted_ascending(arr: List[int]) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_sorted_ascending(arr: List[int]) -> bool: """ Verifies if the given array is sorted in ascending order. Args: arr (List[int]): The array to be checked. Returns: bool: Tru...
magic_evol_110k
87,377
Write a Python function to perform a character replacement operation on a given string. Specifically, the function should replace every occurrence of an exclamation mark (`!`) with an underscore (`_`). The function should return the transformed string. The code should start with: ```python def replace_exclamation_with...
Here is the Python code to solve the given problem in the markdown block: ```python def replace_exclamation_with_underscore(input_string: str) -> str: """ Replace every occurrence of an exclamation mark ('!') in the input string with an underscore ('_'). Args: input_string (str): The input string i...
magic_evol_110k
87,380
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...
magic_evol_110k
87,382
Write a Python function to randomly shuffle a multidimensional array of integers while ensuring that the relative position of elements in each sub-array remains unchanged. The function should take a list of lists (representing the multidimensional array) as input and return the shuffled array. The code should start wi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def shuffle_multidimensional_array(array: List[List[int]]) -> List[List[int]]: """ Shuffles a multidimensional array of integers while preserving the relative order of elements within each ...
magic_evol_110k
87,409
Write a Python function to systematically locate and substitute each instance of a designated text fragment within an alphanumeric sequence. The function should handle cases where the text fragment to be replaced is a substring of another word. The function should also handle cases where the text fragment is at the beg...
Here is the Python code to solve the given problem in the markdown block: ```python import re def replace_text_fragment(string: str, phrase: str, new_string: str) -> str: """ Replaces each instance of a designated text fragment within an alphanumeric sequence. Args: string (str): The original stri...
magic_evol_110k
87,411
Write a Python function to interleave and zip two different lists into a single dictionary, where each key has a tuple as its value. The function should take three lists as input: the first list contains the keys, and the second and third lists contain the values that will form the tuples. The function should return th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Tuple def interleave_lists_to_dict(keys: List[str], values1: List[int], values2: List[str]) -> Dict[str, Tuple[int, str]]: """ Interleaves and zips two different lists into a single dictionary, wh...
magic_evol_110k
87,412
Write a Python function to interchange the first and last elements in a list, the second element with the second last element, the third element with the third last element, and so on. The function should be able to handle lists of any length and data type. The code should start with: ```python from typing import List,...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def swap_elements(lst: List[Any]) -> List[Any]: """ Interchanges the first and last elements in a list, the second element with the second last element, the third element with the third last ele...
magic_evol_110k
87,413
Write a Python function to find all common elements in two sorted arrays without using built-in functions or libraries. The function should efficiently compare the elements of the two arrays using a two-pointer technique. The code should start with: ```python from typing import List def find_common_elements(list1: Lis...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_common_elements(list1: List[int], list2: List[int]) -> List[int]: """ Find all common elements in two sorted arrays using a two-pointer technique. Args: list1 (List[int]): The first...
magic_evol_110k
87,417
Write a Python function to generate all prime numbers within a given range using the Sieve of Eratosthenes method. Additionally, create another function that calculates the prime factorization of every non-prime number within the same range. The functions should handle edge cases where the range might be less than 2. T...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict import math def generate_primes(start: int, end: int) -> List[int]: """ Generate all prime numbers within the given range [start, end] using the Sieve of Eratosthenes method. Args: sta...
magic_evol_110k
87,434
Write a Python function to identify the number that is greater than 100 and appears most frequently in a given list of integers. If there are multiple numbers that satisfy these conditions and have the same frequency, return the smallest number among them. The code should start with: ```python from typing import List ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List from collections import Counter def most_frequent_over_100(arr: List[int]) -> int: """ Identify the number greater than 100 that appears most frequently in the given list. If there are multiple numbe...
magic_evol_110k
87,445
Write a Python function to process a nested dictionary and perform specific operations on its elements. The function should handle variable levels of dictionary nesting. For each integer encountered, multiply it by its order of discovery (starting from 1). For each string encountered, concatenate it to a growing string...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Any, Tuple def process_nested_dict(d: Dict[Any, Any]) -> Tuple[Dict[Any, Any], str]: """ Process a nested dictionary by performing specific operations on its elements. For each integer encountered,...
magic_evol_110k
87,450
Write a Python function to generate a personalized greeting message for a given name. The function should return a string that includes the name provided as an argument. Additionally, ensure that the function does not contain any unused variables or unnecessary code. The code should start with: ```python def generate_...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_greeting(name: str) -> str: """ Generates a personalized greeting message for the given name. Args: name (str): The name to include in the greeting message. Returns: str: A greeting message...
magic_evol_110k
87,451
Write a Python function to generate a list of prime numbers between two given integers `m` and `n` (inclusive). Additionally, write a helper function to determine if a number is prime without using any mathematical functions or packages. The code should start with: ```python def is_prime(num: int) -> bool: """ ...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime(num: int) -> bool: """ Determines if a number is prime. Args: num (int): The number to check for primality. Returns: bool: True if the number is prime, False otherwise. """ if num <...
magic_evol_110k
87,460
Write a Python function to calculate the sum of all elements in a given list of integers. The function should iterate through each element in the list, add them together, and return the total sum. The code should start with: ```python from typing import List def sum_of_elements(lst: 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_elements(lst: List[int]) -> int: """ Calculate the sum of all elements in a given list of integers. Args: lst (List[int]): A list of integers to be summed. Returns: i...
magic_evol_110k
87,462
Write a Python function to calculate the total number of fruits given the quantities of apples and oranges. The function should accept two parameters: one for the number of apples and another for the number of oranges. The function should return the sum of these two quantities. The code should start with: ```python de...
Here is the Python code to solve the given problem in the markdown block: ```python def total_fruits(apples: int, oranges: int) -> int: """ Calculate the total number of fruits given the quantities of apples and oranges. Args: apples (int): The number of apples. oranges (int): The number of...
magic_evol_110k
87,473
Write a Python function to rank a list of tuples based on the character length of the second element in each tuple. The function should return the sorted list of tuples. The code should start with: ```python from typing import List, Tuple def rank_tuples(tuples_list: List[Tuple[str, str]]) -> List[Tuple[str, str]]: ``...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def rank_tuples(tuples_list: List[Tuple[str, str]]) -> List[Tuple[str, str]]: """ Rank a list of tuples based on the character length of the second element in each tuple. Args: tuples...
magic_evol_110k
87,474
Write a Python function that converts a given list comprehension into an equivalent generator comprehension. The function should take a list comprehension as a string and return a generator comprehension as a string. The input list comprehension will always be a simple one-liner with a single `for` loop and an optional...
Here is the Python code to solve the given problem in the markdown block: ```python def convert_list_comp_to_gen_comp(list_comp: str) -> str: """ Converts a given list comprehension string into an equivalent generator comprehension string. Args: list_comp (str): A string representing a list compreh...
magic_evol_110k
87,475
Write a Python function to reverse the elements of a dynamically sized array in place. The function should take a list as input and modify the list such that the first element becomes the last, the second element becomes the second last, and so on. The function should not return any value but should modify the input li...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_array_in_place(array: List[int]) -> None: """ Reverses the elements of the given list in place. Args: array (List[int]): The list of integers to be reversed. Returns: ...
magic_evol_110k
87,479
Write a Python function to implement a smooth clamp function that smoothly clamps a value `x` between `x_min` and `x_max` using an N-order Smoothstep function. The function should return the clamped value with a continuous derivative. The code should start with: ```python import numpy as np def smoothclamp(x: float, x...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def smoothclamp(x: float, x_min: float, x_max: float, N: int) -> float: """ Smoothly clamps a value `x` between `x_min` and `x_max` using an N-order Smoothstep function. Args: x (float): The valu...
magic_evol_110k
87,489
Write a Python function to check if a given string contains all the words in a list of words, regardless of their order and case sensitivity. The function should return `True` if all the words are present in the string, and `False` otherwise. The code should start with: ```python from typing import List def contains_a...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def contains_all_words(s: str, words: List[str]) -> bool: """ Check if the given string contains all the words in the list, regardless of their order and case sensitivity. Args: s (str): The...
magic_evol_110k
87,492
Write a Python function to concatenate a list of textual elements into a single string with a specified delimiter. The function should handle an empty list by returning an empty string. The code should start with: ```python from typing import List def concatenate_with_delimiter(elements: List[str], delimiter: str = ''...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def concatenate_with_delimiter(elements: List[str], delimiter: str = '') -> str: """ Concatenates a list of textual elements into a single string with a specified delimiter. Args: elements (...
magic_evol_110k
87,501
Write a Python function that prints the first 10 natural numbers, calculates the sum of their squares, and computes the average of these numbers. The function should handle potential errors gracefully and return the sum of squares and the average. The code should start with: ```python def natural_numbers_stats() -> tu...
Here is the Python code to solve the given problem in the markdown block: ```python def natural_numbers_stats() -> tuple: """ Prints the first 10 natural numbers, calculates the sum of their squares, and computes the average of these numbers. Handles potential errors gracefully. Returns: tuple:...
magic_evol_110k
87,503
Write a Python function to reverse a given sequence without using any built-in functions for reversing sequences (e.g., `reversed`, `slice`, etc.). The sequence can be a tuple or a list. The function should return the reversed sequence. The code should start with: ```python from typing import Union, Tuple, List def r...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Union, Tuple, List def reverse_sequence(seq: Union[Tuple, List]) -> Union[Tuple, List]: """ Reverses the given sequence without using any built-in functions for reversing sequences. Args: seq (Un...
magic_evol_110k
87,517
Write a Python function to calculate the total number of seats reserved for each flight after considering both bookings and cancellations. The function should take three inputs: a list of bookings, a list of cancellations, and the number of flights `n`. Each booking and cancellation is represented as a list of three in...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def flight_bookings_with_cancellations(bookings: List[List[int]], cancellations: List[List[int]], n: int) -> List[int]: """ Calculate the total number of seats reserved for each flight after considering ...
magic_evol_110k
87,524
Write a Python function that validates scholar data according to a set of predefined rules using advanced Python coding techniques such as decorators and generator expressions. The function should handle large amounts of data efficiently and return a dictionary indicating the validity of each scholar's data. The code ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Any import re def validate_name(name: str) -> bool: """Checks if the given name is valid.""" # The regular expression "^[a-zA-Z ]*$" checks if name only contains alphabets & spaces return bool(re.ma...
magic_evol_110k
87,540
Write a Python function to generate a sequence of Fibonacci numbers that do not exceed a given integer `y`. The function should return a list of these Fibonacci numbers. The code should start with: ```python from typing import List def generate_fibonacci_sequence(y: 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(y: int) -> List[int]: """ Generates a sequence of Fibonacci numbers that do not exceed the given integer `y`. Args: y (int): The upper limit for the Fibonacci...