source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
magic_evol_110k
90,237
Write a Python function to filter out prime numbers from a given list of integers. The function should handle negative numbers, zero, and one appropriately, and should efficiently determine if a number is prime using an optimized approach. The code should start with: ```python from typing import List import math def ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def get_prime_numbers(nums: List[int]) -> List[int]: """ Returns a list of prime numbers from the given list of integers. Args: nums (List[int]): The list of integers to filter f...
magic_evol_110k
90,242
Write a Python function to recursively compare pairs of numbers using various comparison operators and return a list of boolean results. The function should handle a list of comparisons where each comparison is a list containing two numbers and a comparison operator. The comparison operators can include equality (`==`)...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def recursive_compare(list_of_comparisons: List[List[Union[int, str]]]) -> List[bool]: """ Recursively compares pairs of numbers using various comparison operators and returns a list of boolean re...
magic_evol_110k
90,256
Write a Python function to compute the pairwise product of elements in two different lists. The lists contain integers ranging from 2 to 8, with varying lengths. If the lengths of the lists are not equal, the function should only compute the product for the elements up to the length of the shorter list. The function sh...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def pairwise_product(lst1: List[int], lst2: List[int]) -> List[int]: """ Computes the pairwise product of elements in two lists. Args: lst1 (List[int]): The first list of integers. l...
magic_evol_110k
90,276
Write a Python function to iterate through a given dictionary and print each key-value pair using a while loop. The function should handle any dictionary, not just the provided example. The code should start with: ```python from typing import Dict def print_dict_items(dictionary: Dict) -> None: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def print_dict_items(dictionary: Dict) -> None: """ Iterates through a given dictionary and prints each key-value pair using a while loop. Args: dictionary (Dict): The dictionary to iterate ...
magic_evol_110k
90,277
Write a Python function to generate a list of exactly four unique strings, where each string contains at least one uppercase letter, one lowercase letter, and one special character. The strings should not contain any numeric characters. The function should return the list of strings. The code should start with: ```pyt...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random import string def generate_unique_strings() -> List[str]: """ Generates a list of exactly four unique strings, where each string contains at least one uppercase letter, one lowercase le...
magic_evol_110k
90,297
Write a Python function to evaluate a given mathematical expression involving a variable `n` and return the result. The function should take an integer `n` as input and substitute it into the expression `10 - (n + 6)`. The function should return the evaluated result as an integer. The code should start with: ```python...
Here is the Python code to solve the given problem in the markdown block: ```python def evaluate_expression(n: int) -> int: """ Evaluates the mathematical expression 10 - (n + 6) for a given integer n. Args: n (int): The integer value to substitute into the expression. Returns: int: Th...
magic_evol_110k
90,299
Write a Python function to generate a sequence of prime numbers within a specified numerical interval. The function should efficiently determine if a number is prime and return a list of all prime numbers within the given range. The code should start with: ```python def generate_primes_in_range(start: int, end: int) ->...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_prime(n: int) -> bool: """ Check if the number is prime. Args: n (int): The number to check for primality. Returns: bool: True if the number is prime, False otherwise. ...
magic_evol_110k
90,306
Write a Python function to merge two lists of dictionaries into a single consolidated list. Each dictionary in the lists contains key-value pairs representing attributes of an entity, such as 'name' and 'age'. The function should handle cases where the lists may contain dictionaries with the same keys but different val...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def merge_dictionaries(list1: List[Dict[str, any]], list2: List[Dict[str, any]]) -> List[Dict[str, any]]: """ Merges two lists of dictionaries into a single consolidated list. Args: li...
magic_evol_110k
90,340
Write a Python function to reverse the order of elements in a given list. The function should return a new list with the elements in the reverse order. The original list should remain unchanged. The code should start with: ```python from typing import List def reverse_list(input_list: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_list(input_list: List[int]) -> List[int]: """ Reverses the order of elements in the given list and returns a new list with the reversed elements. Args: input_list (List[int]): Th...
magic_evol_110k
90,353
Write a Python function to find the first quintet (five) of prime numbers from a given array of integers. If there are fewer than five prime numbers in the array, return all the prime numbers found. The function should validate the input and handle edge cases appropriately. The function signature should be: ```python ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_primes(my_list: List[int]) -> List[int]: """ Find the first quintet (five) of prime numbers from a given array of integers. If there are fewer than five prime numbers, return all the primes ...
magic_evol_110k
90,368
Write a Python function to remove duplicates from a given list of integers while maintaining the order of the remaining elements and ensuring a time complexity of O(n). The function should exclude all elements that appear more than once in the list. The order of the remaining elements should be identical to the input l...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates(numbers: List[int]) -> List[int]: """ Removes duplicates from a list of integers while maintaining the order of the remaining elements. Only elements that appear more than once ...
magic_evol_110k
90,369
Write a Python function to remove duplicate elements from a given list while preserving the order of the first occurrence of each element. The function should start with: ```python from typing import List def remove_duplicates(lst: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates(lst: List[int]) -> List[int]: """ Removes duplicate elements from a list while preserving the order of the first occurrence of each element. Args: lst (List[int]): The ...
magic_evol_110k
90,370
Write a Python function to create a dictionary that maps each letter of the English alphabet to its corresponding position (1-26) and vice versa. The function should take no arguments and return the dictionary. The code should start with: ```python def create_alphabet_map() -> dict: ```
Here is the Python code to solve the given problem in the markdown block: ```python def create_alphabet_map() -> dict: """ Creates a dictionary that maps each letter of the English alphabet to its corresponding position (1-26) and vice versa. Returns: dict: A dictionary where keys are letters and v...
magic_evol_110k
90,371
Write a Python function to filter and sort elements from a given array based on a specified number. The function should return a new array containing elements that are greater than the specified number, sorted in descending order, and without any duplicate elements. The code should start with: ```python from typing imp...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_and_sort_elements(arr: List[int], num: int) -> List[int]: """ Filters and sorts elements from the given array based on the specified number. Args: arr (List[int]): The array of in...
magic_evol_110k
90,374
Write a Python function to iterate over a given numerical array and return a list of tuples, where each tuple contains the index and the corresponding element of the array. The function should handle arrays of any length and ensure that the output list maintains the order of elements as they appear in the input array. ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def indexed_elements(arr: List[int]) -> List[Tuple[int, int]]: """ Iterates over a given numerical array and returns a list of tuples, where each tuple contains the index and the corresponding...
magic_evol_110k
90,391
Write a Python function to merge two dictionaries into a single dictionary, ensuring that if there are any overlapping keys, the values from the second dictionary should overwrite the values from the first dictionary. The function should support two distinct approaches for merging: one using the `update` method and ano...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def merge_dictionaries(dict1: Dict, dict2: Dict) -> Dict: """ Merge two dictionaries into a single dictionary. If there are overlapping keys, the values from the second dictionary will overwrite the ...
magic_evol_110k
90,392
Write a Python function to create a frequency-based dictionary that counts the occurrence of each word in a given sentence. The function should handle case insensitivity and punctuation. The code should start with: ```python from typing import Dict def word_frequency(sentence: str) -> Dict[str, int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict import string def word_frequency(sentence: str) -> Dict[str, int]: """ Counts the frequency of each word in a given sentence, ignoring case and punctuation. Args: sentence (str): The input s...
magic_evol_110k
90,397
Write a Python function to determine the shortest sequence of commands required to reach a specific target position on an infinite number line using an advanced race car. The car begins at position 0 with a speed of +1 and can traverse negative positions. The car operates automatically based on three commands: "A" (acc...
Here is the Python code to solve the given problem in the markdown block: ```python def racecar(target: int) -> int: """ Calculate the minimum number of commands required to reach a specific target position on an infinite number line. Args: target (int): The target position to reach. Returns: ...
magic_evol_110k
90,427
Write a Python function to generate a list of all prime numbers up to and including a given integer `n` using the Sieve of Eratosthenes algorithm. The function should return a list of these prime numbers. The code should start with: ```python from typing import List def sieve_of_eratosthenes(n: int) -> List[int]: ```...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sieve_of_eratosthenes(n: int) -> List[int]: """ Generate a list of all prime numbers up to and including a given integer n using the Sieve of Eratosthenes algorithm. Args: n (int): The u...
magic_evol_110k
90,430
Write a Python function to calculate the number of diagonals in a regular polygon given the number of sides. The formula to calculate the number of diagonals in a polygon is `(n * (n - 3)) / 2`, where `n` is the number of sides. The function should take an integer `n` as input and return the number of diagonals as an i...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_diagonals(n: int) -> int: """ Calculate the number of diagonals in a regular polygon given the number of sides. Args: n (int): The number of sides of the polygon. Returns: int: The number ...
magic_evol_110k
90,436
Write a Python function to transform a dataset from long form to wide form by adding a column that lists the lambs in sequential order for each ewe. The dataset is represented as a list of dictionaries, where each dictionary contains the keys 'ewe_id' and 'lamb_id'. The function should return a list of dictionaries whe...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def transform_to_wide_form(dataset: List[Dict[str, int]]) -> List[Dict[str, List[int]]]: """ Transforms a dataset from long form to wide form by adding a column that lists the lambs in sequential o...
magic_evol_110k
90,439
Write a Python function to find the length of the longest arithmetic subsequence in a given array `arr` with a specified difference `difference`. An arithmetic subsequence is a sequence of numbers where the difference between consecutive elements is constant and equal to `difference`. The function should return the len...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def longest_arithmetic_subsequence(arr: List[int], difference: int) -> int: """ Calculate the length of the longest arithmetic subsequence in the given array with the specified difference. Args: ...
magic_evol_110k
90,445
Write a Python function to generate a random 4-digit number (from 1000 to 9999) and return it. The function should ensure that the generated number is within the specified range and should be able to handle multiple calls to generate different numbers each time. The code should start with: ```python import random def...
Here is the Python code to solve the given problem in the markdown block: ```python import random def generate_random_4_digit_number() -> int: """ Generates a random 4-digit number (from 1000 to 9999). Returns: int: A random 4-digit number. """ # Generate a random integer between 1000 and ...
magic_evol_110k
90,454
Write a Python function to create a vector (list) with specific numerical entries in a given order and return it. The function should accept a variable number of integer arguments and return a list containing these integers in the same order they were provided. The code should start with: ```python from typing import ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def create_vector(*args: int) -> List[int]: """ Creates a vector (list) with specific numerical entries in the given order. Args: *args (int): Variable number of integer arguments. Retu...
magic_evol_110k
90,468
Write a Python function to perform a linear search on a given array. The function should return the index of the first occurrence of the search value if it is found in the array, or -1 if the search value is not present in the array. The code should start with: ```python from typing import List def linear_search(array...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def linear_search(array: List[int], search_value: int) -> int: """ Perform a linear search on the given array to find the index of the first occurrence of the search value. Args: array (List...
magic_evol_110k
90,469
Write a Python function to check if a given list of integers is sorted in ascending order. The function should return `True` if the list is sorted, and `False` otherwise. The code should start with: ```python from typing import List def is_list_sorted(lst: List[int]) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_list_sorted(lst: List[int]) -> bool: """ Checks if a given list of integers is sorted in ascending order. Args: lst (List[int]): The list of integers to check. Returns: b...
magic_evol_110k
90,472
Write a Python function to find the longest string in a given list of strings. If there are multiple strings with the same maximum length, return the first one that appears in the list. If the list is empty, return `None`. The code should start with: ```python from typing import List, Optional def find_longest_string...
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 the longest string in a given list of strings. If there are multiple strings with the same maximum length, returns t...
magic_evol_110k
90,475
Write a Python function to remove duplicate elements from a given list, ensuring that only the first occurrence of each element is retained. The function should return a new list with the duplicates removed. The code should start with: ```python from typing import List def remove_duplicates(lst: List[int]) -> List[int...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates(lst: List[int]) -> List[int]: """ Removes duplicate elements from a list, keeping only the first occurrence of each element. Args: lst (List[int]): The input list from ...
magic_evol_110k
90,480
Write a Python function to find the unique positive and negative integers in a given array, calculate the summation of all powers of those unique integers, and then multiply these summations with the count of unique positive and negative integers separately. The function should take three parameters: an integer array `...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def unique_powers_sum_and_mult(arr: List[int], p: int, q: int) -> Optional[int]: """ Given an integer array arr, and two integer parameters p and q, this function returns the sum of unique posi...
magic_evol_110k
90,489
Write a Python function to calculate the factorial of each element in a given tuple and append the results to a specific list. The function should handle tuples containing zero and negative numbers, and return an error message if the tuple is empty. The function should start with: ```python from typing import List, Tup...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple import math def calculate_factorials(tup: Tuple[int], result_list: List[int]) -> List[int]: """ Calculate the factorial of each element in a given tuple and append the results to a specific list. ...
magic_evol_110k
90,511
Write a Python function to convert any given string representation into snake case notation. Snake case is a naming style where words are separated by underscores and all letters are in lowercase. The function should handle strings with mixed cases, numbers, and special characters. Special characters should be removed,...
Here is the Python code to solve the given problem in the markdown block: ```python def convert_to_snake_case(s: str) -> str: """ Converts a given string into snake case notation. Args: s (str): The input string to be converted. Returns: str: The string converted to snake case. """...
magic_evol_110k
90,520
Write a Python function to insert a delimiter between elements of a list of integers, ensuring that the delimiter is not appended after the last element. Additionally, create a wrapper function that takes a tuple of two integers as delimiters and applies the first function to the list of integers using each delimiter i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def insert_delimiter(numbers: List[int], delimiter: int) -> List[int]: """ Insert a delimiter between each element of a list of integers, excluding the last element. Args: numbers: A ...
magic_evol_110k
90,529
Write a Python function to remove duplicate elements from a given list while preserving the order of the first occurrence of each element. The function should be efficient and handle lists of various sizes. The code should start with: ```python from typing import List def remove_duplicates_preserve_order(input_list: L...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates_preserve_order(input_list: List[int]) -> List[int]: """ Removes duplicate elements from the input list while preserving the order of the first occurrence of each element. Args:...
magic_evol_110k
90,539
Write a Python function to calculate the Levenshtein distance (also known as edit distance) between two strings using the Wagner-Fisher algorithm. The Levenshtein distance is the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one string into the other. The function...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def levenshtein_distance(str1: str, str2: str) -> int: """ Calculate the Levenshtein distance between two strings using the Wagner-Fisher algorithm. Args: str1 (str): The first string. ...
magic_evol_110k
90,562
Write a Python function to merge two sorted lists into a single sorted list without using built-in sort functions. The function should start with: ```python from typing import List def merge_sorted_lists(list1: List[int], list2: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sorted_lists(list1: List[int], list2: List[int]) -> List[int]: """ Merges two sorted lists into a single sorted list without using built-in sort functions. Args: list1 (List[int]):...
magic_evol_110k
90,576
Write a Python function to determine if an array includes any occurrence of the `None` value. The function should be efficient and handle various edge cases, such as empty arrays or arrays with only `None` values. The function should also be able to handle large arrays efficiently. The code should start with: ```pytho...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def has_none_in_array(arr: List[int]) -> bool: """ Determines if an array includes any occurrence of the None value. Args: arr (List[int]): The array to check for the presence of None. ...
magic_evol_110k
90,584
Write a Python function to concatenate two strings, 'Good' and ' day', and then replace the word 'Good' with 'Beautiful' in the resulting string. The function should return the modified string. The code should start with: ```python def create_greeting() -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def create_greeting() -> str: """ Concatenates the strings 'Good' and ' day', then replaces 'Good' with 'Beautiful' in the resulting string. Returns: str: The modified string after concatenation and replacement. ...
magic_evol_110k
90,588
Write a Python function to flatten a nested list, remove duplicates, and sort the final list in descending order. The function should handle lists with varying levels of nesting and ensure that the final output is a sorted list of unique elements in descending order. The code should start with: ```python from typing i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def flatten_and_sort(nested_list: List) -> List[int]: """ Flattens a nested list, removes duplicates, and sorts the final list in descending order. Args: nested_list (List): A nested list co...
magic_evol_110k
90,599
Write a Python function to calculate the total cost to acquire a specified number of stamps, given the initial number of stamps and their total cost. The function should assume that the cost per stamp remains constant. The code should start with: ```python def calculate_total_cost(initial_stamps: int, initial_cost: fl...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_total_cost(initial_stamps: int, initial_cost: float, goal_stamps: int) -> float: """ Calculate the total cost to acquire a specified number of stamps, given the initial number of stamps and their total cost. A...
magic_evol_110k
90,602
Write a Python function to compute the Euclidean distance between two points in n-dimensional space. The function should accept two tuples or lists representing the coordinates of the points. Ensure that the function performs input validation to check if the inputs are tuples or lists and if they have the same dimensio...
Here is the Python code to solve the given problem in the markdown block: ```python import math from typing import Union def euclidean_distance(point1: Union[tuple, list], point2: Union[tuple, list]) -> Union[float, str]: """ Compute the Euclidean distance between two points in n-dimensional space. Args: ...
magic_evol_110k
90,610
Write a Python function to count the number of even and odd digits for each number in a given list of integers. The function should return a list of tuples, where each tuple contains the count of even digits and the count of odd digits for the corresponding number in the input list. The code should start with: ```pyth...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def count_even_odd_digits(nums: List[int]) -> List[Tuple[int, int]]: """ Counts the number of even and odd digits for each number in the given list. Args: nums (List[int]): A list of ...
magic_evol_110k
90,613
Write a Python function to sort a list of decimal numbers in descending order. The function should take a list of decimal numbers as input and return the sorted list. The code should start with: ```python from typing import List def sort_decimals_descending(decimal_numbers: List[float]) -> List[float]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_decimals_descending(decimal_numbers: List[float]) -> List[float]: """ Sorts a list of decimal numbers in descending order. Args: decimal_numbers (List[float]): A list of decimal num...
magic_evol_110k
90,619
Write a Python function to segregate and sort a given list into two distinct sections based on a specified threshold value. The function should return two lists: one containing elements less than or equal to the threshold, and the other containing elements greater than the threshold. Both lists should be sorted in asce...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def segregate_and_sort(lst: List[int], threshold: int) -> Tuple[List[int], List[int]]: """ Segregates and sorts a list into two sections based on a specified threshold value. Args: ls...
magic_evol_110k
90,627
Write a Python function to determine the minimum number of instructions required for a race car to reach a given target position on an infinite number line. The car starts at position 0 with an initial speed of +1 and can receive three types of instructions: - **"A" (accelerate)**: The car's position increases by its c...
Here is the Python code to solve the given problem in the markdown block: ```python def min_instructions_to_reach_target(target: int) -> int: """ Calculate the minimum number of instructions required for a race car to reach a given target position. Args: target (int): The target position on the inf...
magic_evol_110k
90,628
Write a Python function to calculate the average of a list of numbers, handling missing values (NaN) and negative numbers. The function should ignore NaN values and optionally ignore negative numbers based on a boolean flag. The code should start with: ```python from typing import List import numpy as np def calculate...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import numpy as np def calculate_average(arr: List[float], ignore_negative: bool = False) -> float: """ Calculate the average of a list of numbers, ignoring NaN values and optionally ignoring negative nu...
magic_evol_110k
90,633
Write a Python function to reverse a given unidimensional array of fundamental elements without using any built-in or predefined algorithms for reversing the array. The function should manually swap elements from the start and end of the array, moving towards the center until the entire array is reversed. The code sho...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_array_manual(input_array: List[int]) -> List[int]: """ Reverses a given unidimensional array of fundamental elements without using any built-in or predefined algorithms. Args: in...
magic_evol_110k
90,641
Refactor the given Python code to eliminate redundancy and improve efficiency. Identify and correct any logical discrepancies in the code. The task is to rewrite the code so that it performs the same operations but in a more efficient and logically sound manner. The code should start with: ```python def calculate_y(x: ...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_y(x: int) -> int: """ Calculate the value of y based on the value of x. Args: x (int): The input value for which to calculate y. Returns: int: The calculated value of y. """ if x >...
magic_evol_110k
90,663
Write a Python function to find the maximum value element in a 2-dimensional array and determine its position (row and column index). The function should return the maximum value along with its position as a tuple. The code should start with: ```python from typing import List, Tuple def find_max_and_position(array: Li...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_max_and_position(array: List[List[int]]) -> Tuple[int, Tuple[int, int]]: """ Finds the maximum value element in a 2-dimensional array and determines its position (row and column index). ...
magic_evol_110k
90,673
Create a Python class `MyList` that implements a custom iterator and methods to retrieve elements from the list based on the index and to return elements that fulfill certain conditions specified by a lambda function. The class should include the following methods: 1. `__init__`: Initializes the list. 2. `add`: Adds an...
Here is the Python code to solve the given problem in the markdown block: ```python class MyList: def __init__(self): """ Initializes the list. """ self.list = [] def add(self, item): """ Adds an element to the list. Args: item: The element t...
magic_evol_110k
90,675
Write a Python function called `merge_alternating` that takes two lists of integers, `list1` and `list2`, as inputs and returns a new list. In the new list, elements from `list1` and `list2` should alternate, beginning with the first element of `list1`. If one list is longer than the other, the remaining elements of th...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_alternating(list1: List[int], list2: List[int]) -> List[int]: """ Merge two input lists `list1` and `list2` by alternating their elements in the new list. Args: list1 (List[int]): ...
magic_evol_110k
90,677
Write a Python function to multiply each element of a given list of integers by a specified non-zero integer. The function should be optimized to handle large lists efficiently and should correctly handle cases where the list contains negative integers or zeros. The function should start with: ```python from typing imp...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def multiply_list(n: int, lst: List[int]) -> List[int]: """ Multiplies each element of the given list by the specified non-zero integer. Args: n (int): The non-zero integer to multiply each ...
magic_evol_110k
90,684
Write a Python function to transform a list of numbers by applying a given transformation function to each element. The transformation function should be applied to each element in the list, and the function should return a new list containing the transformed elements. The code should start with: ```python from typing ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Callable def transform_list(numbers: List[int], transformation: Callable[[int], int]) -> List[int]: """ Applies a given transformation function to each element in the list of numbers and returns a new l...
magic_evol_110k
90,688
Write a Python function to generate and print the first `n` prime numbers correctly and efficiently. The function should use a `while` loop control structure to generate the prime numbers. The function should also ensure that the prime number generation is optimized to avoid unnecessary computations. The code should st...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_primes(n: int) -> list: """ Generate the first n prime numbers. Args: n (int): The number of prime numbers to generate. Returns: list: A list containing the first n prime numbers. """ ...
magic_evol_110k
90,690
Write a Python function to rearrange a given list in descending order without duplicates. The function should take a list of integers as input and return a new list with the elements sorted in descending order, with all duplicates removed. The code should start with: ```python from typing import List def rearrange_de...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def rearrange_descending_unique(lst: List[int]) -> List[int]: """ Rearranges the given list in descending order without duplicates. Args: lst (List[int]): The list of integers to rearrange. ...
magic_evol_110k
90,700
Write a Python function to perform Caesar Cipher encryption on a given text string with a specified shift value. The Caesar Cipher is a type of substitution cipher where each letter in the plaintext is shifted a certain number of places down or up the alphabet. Non-alphabet characters should remain unchanged. The code...
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 method with the specified shift value. Args: text (str): The text to be encrypted. shift (int): Th...
magic_evol_110k
90,719
Write a Python function to find an index mapping `P` from list `A` to list `B`, where `B` is an anagram of `A`. The mapping should be such that the sum of the indices in the mapping `P` is minimized. If there are multiple mappings with the same minimum sum, output any of them. The function should start with: ```python ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List from collections import defaultdict def find_anagram_mappings(A: List[int], B: List[int]) -> List[int]: """ Find an index mapping `P` from list `A` to list `B`, where `B` is an anagram of `A`. The ma...
magic_evol_110k
90,720
Write a Python function that converts a dictionary into a tuple where each key-value pair in the dictionary is represented as a tuple within the main tuple. The function should ensure that the final output retains the tuple data structure. The code should start with: ```python from typing import Dict, Tuple def dict_t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Tuple def dict_to_tuple(dict_obj: Dict) -> Tuple[Tuple[str, int], ...]: """ Converts a dictionary into a tuple where each key-value pair is represented as a tuple within the main tuple. Args: ...
magic_evol_110k
90,746
Write a Python function that performs different operations based on a boolean condition `cond`. If `cond` is `True`, the function should perform a series of mathematical operations and list manipulations on a predefined list. If `cond` is `False`, the function should perform different mathematical operations and list m...
Here is the Python code to solve the given problem in the markdown block: ```python def conditional_operations(cond=None): """ Perform different operations based on a boolean condition `cond`. If `cond` is `True`, the function performs a series of mathematical operations and list manipulations on a predefi...
magic_evol_110k
90,747
Write a Python function to reverse the order of elements in a given list. The function should accept a list as input and return a new list with the elements in the reversed sequence. The code should start with: ```python from typing import List def reverse_list(array: List[str]) -> List[str]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_list(array: List[str]) -> List[str]: """ Reverses the order of elements in the given list. Args: array (List[str]): The list of elements to be reversed. Returns: Lis...
magic_evol_110k
90,772
Write a Python function to find the greatest common divisor (GCD) of two given integers using the Euclidean algorithm. The function should handle both positive and negative integers. The code should start with: ```python def gcd(a: int, b: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def gcd(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. Returns: ...
magic_evol_110k
90,775
Write a Python function to generate a list of prime numbers up to a given limit `n` using the Sieve of Eratosthenes method. The function should return a list of all prime numbers less than `n`. The code should start with: ```python from typing import List def sieve_of_eratosthenes(n: int) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sieve_of_eratosthenes(n: int) -> List[int]: """ Generate a list of prime numbers up to a given limit n using the Sieve of Eratosthenes method. Args: n (int): The upper limit up to which ...
magic_evol_110k
90,795
Write a Python function to calculate the investments made by each partner (technology, financial, marketing) and the investments made by each other investor in a startup. The total investment is $2,000,000. The technology partner invested 30% more than the financial partner, the marketing partner invested 20% less than...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_investments() -> tuple: """ Calculate the investments made by each partner (technology, financial, marketing) and the investments made by each other investor in a startup. Returns: tuple: A tuple conta...
magic_evol_110k
90,796
Write a Python function to sort a list of dictionaries based on two keys: `income` and `age`. The `income` key should be binned into ranges of 10,000 units (e.g., income values between 0 and 9,999 should be in the same bin, values between 10,000 and 19,999 in the next bin, and so on). The sorting should first prioritiz...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict import math def sort_by_income_and_age(data: List[Dict[str, int]]) -> List[Dict[str, int]]: """ Sorts a list of dictionaries based on binned income and age. Args: data (List[Dict[str, ...
magic_evol_110k
90,799
Write a Python function to determine the maximum value between two given integers `x` and `y` using a streamlined computational approach. The function should return the larger of the two values. The code should start with: ```python def get_max_value(x: int, y: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def get_max_value(x: int, y: int) -> int: """ Returns the maximum value between two given integers. Args: x (int): The first integer. y (int): The second integer. Returns: int: The larger of the...
magic_evol_110k
90,805
Write a Python function to identify the index positions of all integers in a given list that are divisible by 3. The function should also generate a log file containing the index positions of any non-integer elements in the list. The index positions should be 1-based, meaning they start from 1 instead of 0. The code s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def find_divisible_by_three(numbers: List[Union[int, str]]) -> List[int]: """ Identify the index positions of all integers in the given list that are divisible by 3. Also, generate a log file ...
magic_evol_110k
90,810
Write a Python function to find the longest common subsequence (LCS) between two given strings `s1` and `s2`. The function should return the LCS as a string. The code should start with: ```python def longest_common_subsequence(s1: str, s2: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def longest_common_subsequence(s1: str, s2: str) -> str: """ Finds the longest common subsequence (LCS) between two strings s1 and s2. Args: s1 (str): The first string. s2 (str): The second string. Retu...
magic_evol_110k
90,813
Write a Python function to concatenate a list of strings into a single string using the `join` method. The function should accept a list of strings and an optional separator string. If no separator is provided, the function should use an empty string as the default separator. The function should return the concatenated...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def concatenate_strings(strings: List[str], separator: Optional[str] = None) -> str: """ Concatenates a list of strings into a single string using the specified separator. Args: st...
magic_evol_110k
90,826
Write a Python function to replace occurrences of a substring in a given string with a new substring, but only for the first `count` occurrences. If `count` is not provided, replace all occurrences. The function should handle cases where `count` is negative or zero, and should return the modified string. The code shou...
Here is the Python code to solve the given problem in the markdown block: ```python def replace_substring(s: str, old: str, new: str, count: int = -1) -> str: """ Replaces occurrences of a substring in a given string with a new substring. Args: s (str): The original string in which to perform the r...
magic_evol_110k
90,827
Write a Python function to identify prime numbers from a given list and ensure the input list is formatted correctly. If the list contains elements that are not integers, or if any other type of exception occurs during the extraction, the function should display an appropriate error message. The function should return ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List from math import sqrt def prime_numbers_in_list(input_list: List[int]) -> List[int]: """ Identify prime numbers from a given list and ensure the input list is formatted correctly. Args: inpu...
magic_evol_110k
90,837
Write a Python function to create a new list where each element is derived from the initial and terminal integer values of each subarray found within a two-dimensional array. The function should take a 2D list as input and return a new 2D list with the specified elements. 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 def extract_first_last_elements(two_d_array: List[List[int]]) -> List[List[int]]: """ Extracts the first and last elements from each subarray in a 2D array and returns a new 2D array with these elements....
magic_evol_110k
90,842
Write a Python function that increments a counter variable by either a fixed value (20) or a predetermined value stored in another variable, without manually specifying the value to increment. The function should accept a boolean flag to determine which value to use for the increment. The code should start with: ```py...
Here is the Python code to solve the given problem in the markdown block: ```python counter = 0 increment_val = 20 # or whatever value you like def increment_counter(use_fixed_value: bool) -> int: """ Increments the global counter variable by either a fixed value (20) or a predetermined value stored in increm...
magic_evol_110k
90,843
Write a Python function to generate a list of all odd integers within a given numerical range. The function should take two parameters: `start` and `end`, representing the inclusive range of numbers to consider. The function should return a list of all odd integers within this range. The code should start with: ```pyt...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def get_odd_numbers(start: int, end: int) -> List[int]: """ Generate a list of all odd integers within a given range [start, end]. Args: start (int): The starting number of the range (inclus...
magic_evol_110k
90,857
Write a Python function to encode and decode a given string by advancing and retracting its alphabetic characters by two positions in the ASCII table, respectively. Non-alphabetic characters should remain unchanged. The code should start with: ```python def encode_string(text: str) -> str: def decode_string(text: str) ...
Here is the Python code to solve the given problem in the markdown block: ```python def encode_string(text: str) -> str: """ Encodes a given string by advancing each alphabetic character by two positions in the ASCII table. Non-alphabetic characters remain unchanged. Args: text (str): The strin...
magic_evol_110k
90,867
Write a Python function to check if a given word is a palindrome using a memory-efficient algorithm. The function should compare characters from the start and end of the word moving towards the middle, and return `True` if the word is a palindrome and `False` otherwise. The function should handle both uppercase and low...
Here is the Python code to solve the given problem in the markdown block: ```python def is_palindrome(word: str) -> bool: """ Check if a given word is a palindrome using a memory-efficient algorithm. Args: word (str): The word to check for palindrome property. Returns: bool: True if th...
magic_evol_110k
90,887
Write a Python function to multiply all the odd integers within a given list and return the product. The function should handle lists of any length, including empty lists, and should return 1 if the list contains no odd numbers. The code should start with: ```python from typing import List def multiply_odd_numbers(num...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def multiply_odd_numbers(numbers: List[int]) -> int: """ Multiplies all the odd integers within a given list and returns the product. Args: numbers (List[int]): A list of integers. Retu...
magic_evol_110k
90,889
Write a Python function to perform ternary search on a sorted array of integers. The function should return the index of the target element if it exists in the array, otherwise return -1. Additionally, handle edge cases where the array is empty or contains duplicate integers. The code should start with: ```python from ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def ternary_search(arr: List[int], x: int) -> int: """ Perform ternary search on a sorted array to find the index of the target element. Args: arr (List[int]): The sorted array of integers. ...
magic_evol_110k
90,898
Write a Python function to calculate the product of all elements in a given list of integers. The function should handle lists of any length, including empty lists. If the list is empty, the function should return 1 as the product. The code should start with: ```python from typing import List def product_of_elements(...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def product_of_elements(arr: List[int]) -> int: """ Calculate the product of all elements in a given list of integers. Args: arr (List[int]): The list of integers whose product is to be calc...
magic_evol_110k
90,903
Write a Python function to encrypt a text message using a given key. The encryption should shift each alphabetic character in the message by the key value in the alphabet. Non-alphabetic characters should remain unchanged. The function should be case-sensitive, meaning that uppercase and lowercase letters should be tre...
Here is the Python code to solve the given problem in the markdown block: ```python def encrypt_message(msg: str, key: int) -> str: """ Encrypts a text message using a given key by shifting each alphabetic character by the key value in the alphabet. Args: msg (str): The text message to be encrypted...
magic_evol_110k
90,905
Write a Python function to rearrange a given list in descending order without duplicates and display each number's frequency in the original list. The function should return a tuple containing the rearranged list and a dictionary with the frequency of each number. 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, Dict, Tuple from collections import Counter def rearrange_and_count(lst: List[int]) -> Tuple[List[int], Dict[int, int]]: """ Rearranges the given list in descending order without duplicates and counts t...
magic_evol_110k
90,921
Write a Python function to calculate the binomial coefficient \( C(n, m) \) for given integers \( n \) and \( m \) (where \( m \leq n \)). The function should efficiently handle large inputs and incorporate memoization to optimize execution. Additionally, the function should include a mechanism to manage potential memo...
Here is the Python code to solve the given problem in the markdown block: ```python def binomial_coefficient(n: int, m: int) -> int: """ Calculate the binomial coefficient C(n, m) using dynamic programming with memoization. Args: n (int): The total number of items. m (int): The number of it...
magic_evol_110k
90,931
Write a Python function to evaluate a logical condition and perform an arithmetic operation based on the result. The function should take three integers `a`, `b`, and `c` as input and return the product of `a`, `b`, and `c` if either `a` is greater than `b` or `b` is less than `c`. Otherwise, it should return `None`. ...
Here is the Python code to solve the given problem in the markdown block: ```python def evaluate_condition_and_multiply(a: int, b: int, c: int) -> int: """ Evaluates a logical condition and performs an arithmetic operation based on the result. Args: a (int): The first integer. b (int): The ...
magic_evol_110k
90,936
Write a Python function that generates and yields the first N numbers from the Fibonacci sequence using a generator. The function should be designed to yield each Fibonacci number one at a time, rather than returning a list of all numbers at once. The function should start with: ```python def generate_fibonacci(n: int)...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_fibonacci(n: int): """ Generates and yields the first N numbers from the Fibonacci sequence. Args: n (int): The number of Fibonacci numbers to generate. Yields: int: The next Fibonacci numb...
magic_evol_110k
90,939
Write a Python function to dismantle a given character sequence using a specified delimiter and return the resulting list of substrings. The function should handle cases where the delimiter is not present in the sequence by returning the sequence as a single-element list. The function should also handle empty sequences...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def dismantle_sequence(sequence: str, delimiter: str) -> List[str]: """ Dismantles a given character sequence using the specified delimiter and returns the resulting list of substrings. Args: ...
magic_evol_110k
90,944
Write a Python function to calculate the mean value of a collection of whole numbers within the integer domain. The function should handle collections with zero elements by returning 0. The code should start with: ```python from typing import List def calculate_mean(numbers: List[int]) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_mean(numbers: List[int]) -> float: """ Calculate the mean value of a collection of whole numbers. Args: numbers (List[int]): A list of integers for which the mean is to be calc...
magic_evol_110k
90,958
Write a Python function to find the maximum potential score achievable from a given set of numerical entities and their corresponding score attributions. The function should take two lists as input: one representing the numerical entities and the other representing their corresponding scores. The function should return...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_max_score(numerical_set: List[int], score_attributions: List[int]) -> int: """ Finds the maximum potential score achievable from a given set of numerical entities and their corresponding scores....
magic_evol_110k
90,969
Write a Python function to filter a list of strings based on a regular expression pattern that matches sequences composed solely of uppercase alphabets and numerical figures. The function should return a list of strings that match the pattern. The code should start with: ```python from typing import List import re de...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import re def filter_sequences(data: List[str]) -> List[str]: """ Filters a list of strings to return only those that match a specific regular expression pattern. The pattern matches sequences compos...
magic_evol_110k
90,970
Write a Python function to find and return the second smallest element in a given list. If the list has fewer than two elements or if all elements are the same, the function should return `None`. The function should be efficient and avoid modifying the original list. The code should start with: ```python from typing i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def next_smallest(lst: List[int]) -> Optional[int]: """ Find and return the second smallest element in the given list. Args: lst (List[int]): The list of integers from which to fin...
magic_evol_110k
90,976
Write a Python function to print numbers from 0 to 9 using a `while` loop instead of a `for` loop. The function should be named `print_numbers_while_loop`. Additionally, provide a function `print_numbers_for_loop` that uses a `for` loop to achieve the same result. Both functions should be well-documented with a docstri...
Here is the Python code to solve the given problem in the markdown block: ```python def print_numbers_while_loop(): """ Prints numbers from 0 to 9 using a while loop. Parameters: None Returns: None """ a = 0 while a < 10: print(a) a += 1 def print_numbers_f...
magic_evol_110k
90,992
Write a Python function to identify and return the string with the longest length from a given list of strings. If there are several strings with the same length, return the one that appeared first. If the list is empty, return `None`. The function should be robust and handle various edge cases, including lists with du...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def longest_string(strings: List[str]) -> Optional[str]: """ Identify and return the string with the longest length from a given list of strings. If there are several strings with the same ...
magic_evol_110k
90,995
Write a Python function to determine if a given string is a palindrome without using any built-in string reversal functions or methods. The function should compare characters from the beginning and end of the string moving towards the center. The code should start with: ```python def is_palindrome(string: str) -> bool...
Here is the Python code to solve the given problem in the markdown block: ```python def is_palindrome(string: str) -> bool: """ Determines if a given string is a palindrome without using any built-in string reversal functions or methods. Args: string (str): The string to check for palindrome proper...
magic_evol_110k
90,997
Write a Python function to split a given string into an array of individual lexical terms (words) based on whitespace. The function should handle multiple consecutive spaces and leading/trailing spaces gracefully, ensuring that the resulting list contains only non-empty strings. The code should start with: ```python f...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def split_into_words(text: str) -> List[str]: """ Splits a given string into an array of individual lexical terms (words) based on whitespace. Args: text (str): The input string to be split ...
magic_evol_110k
91,020
Write a Python function to segregate prime numbers and their respective indices from a given list of positive integers. The function should return two lists: one containing only the prime numbers and the other containing their respective indices in the original list. The code should start with: ```python from typing i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def is_prime(n: int) -> bool: """ Check if a number is prime. Args: n (int): The number to check for primality. Returns: bool: True if the number is prime, False otherwis...
magic_evol_110k
91,042
Write a Python function to detect and extract all valid email addresses from a given text. The function should use regular expressions to identify email addresses that match the pattern of a local part (before the '@' symbol) followed by an '@' symbol and a domain part (after the '@' symbol). The local part can contain...
Here is the Python code to solve the given problem in the markdown block: ```python import re from typing import List def extract_emails(text: str) -> List[str]: """ Extracts all valid email addresses from the given text using a regular expression. Args: text (str): The text from which to extract ...
magic_evol_110k
91,048
Write a Python function to extract the domain name from a given email address. The function should handle various email formats and return the domain part of the email address. The code should start with: ```python def extract_domain_from_email(email: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def extract_domain_from_email(email: str) -> str: """ Extracts the domain name from a given email address. Args: email (str): The email address from which to extract the domain name. Returns: str: The d...
magic_evol_110k
91,063
Write a Python function to convert a given date and time string in the format 'Day-Month-Year Hours:Minutes' into a specific layout that presents 'Day-Month-Year and Hours:Minutes'. The input date and time string will be in the format 'DD-MM-YYYY HH:MM'. The function should return the formatted date and time string. T...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import datetime def convert_datetime_format(original_time: str) -> str: """ Converts a given date and time string in the format 'DD-MM-YYYY HH:MM' into a specific layout 'Day-Month-Year and Hours:Minutes'. Ar...
magic_evol_110k
91,065
Write a Python function to find the highest numerical value from a given list of numerical values. The function should handle lists of integers and floats. The code should start with: ```python from typing import List, Union def find_max_value(numbers: List[Union[int, float]]) -> Union[int, float]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def find_max_value(numbers: List[Union[int, float]]) -> Union[int, float, None]: """ Find the highest numerical value from a given list of numerical values. Args: numbers (List[Union[...
magic_evol_110k
91,069
Write a Python function that takes a list of integers as input and returns a tuple containing two elements: a list of all prime numbers from the input list, and the sum of all those prime numbers. The function should use the Sieve of Eratosthenes algorithm to efficiently determine prime numbers, ensuring that the time ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def sieve_of_eratosthenes(n: int) -> List[int]: """ Generate a list of prime numbers up to n using the Sieve of Eratosthenes algorithm. Args: n (int): The upper limit for generating p...
magic_evol_110k
91,092
Write a Python function to decode a permutation cipher composed of the characters 'D' and 'I'. The cipher represents a sequence of numbers from 1 to n (where n is the length of the cipher plus one) that follow specific rules: 'D' signifies a descending correlation between two numerals, while 'I' indicates an ascending ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def decode_permutation_cipher(cipher: str) -> List[int]: """ Decodes a permutation cipher composed of 'D' and 'I' characters to find the smallest lexicographical permutation of numbers [1, 2, ..., n]...
magic_evol_110k
91,105
Write a Python function to replace all instances of a specified character with another specified character in a given string, without using built-in replace functions. The function should iterate through the string and construct a new string with the replacements. The code should start with: ```python def replace_char...
Here is the Python code to solve the given problem in the markdown block: ```python def replace_char(string: str, old_char: str, new_char: str) -> str: """ Replaces all instances of a specified character with another specified character in a given string. Args: string (str): The input string in whi...
magic_evol_110k
91,106
Write a Python function to convert a list of tuples into a dictionary where each tuple's second element is used as the key and the first element is used as the value. Ensure that the function handles cases where the list might be empty or contain duplicate keys. The code should start with: ```python from typing import...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def convert_tuple_list_to_dict(tuple_list: List[Tuple[str, str]]) -> Dict[str, str]: """ Converts a list of tuples into a dictionary where each tuple's second element is used as the key and ...