source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
magic_evol_110k
83,654
Write a Python function to calculate the minimum number of circular tables required to seat a given number of attendees, where each table has a fixed seating capacity. The function should handle any positive integer input for the number of attendees and the seating capacity per table. The code should start with: ```py...
Here is the Python code to solve the given problem in the markdown block: ```python import math def min_tables_required(num_attendees: int, capacity_per_table: int) -> int: """ Calculate the minimum number of circular tables required to seat a given number of attendees, where each table has a fixed seating...
magic_evol_110k
83,662
Write a Python function to determine if it is possible to select `n` disjoint subarrays from a given integer array `nums` such that each subarray corresponds to the elements of the `ith` subarray in a given two-dimensional integer array `groups` (0-indexed), and the subarrays in `nums` must maintain the same order as i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def can_choose_subarrays(groups: List[List[int]], nums: List[int]) -> bool: """ Determines if it is possible to select `n` disjoint subarrays from `nums` such that each subarray corresponds to the elemen...
magic_evol_110k
83,674
Write a Python function to reverse the order of keys in a given dictionary and replace the dictionary values with their corresponding ASCII values. The dictionary will contain alphabets as keys and numbers as their corresponding values. The function should start with: ```python from typing import Dict def reverse_and_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def reverse_and_ascii_values(dictionary: Dict[str, int]) -> Dict[str, int]: """ Reverses the order of keys in the given dictionary and replaces the values with their corresponding ASCII values. Args...
magic_evol_110k
83,680
Write a Python function to calculate the number of ways to climb a staircase with `n` steps, where you can either take 1 step or 2 steps at a time. The function should return the total number of distinct ways to reach the top of the staircase. The code should start with: ```python def climb_stairs(n: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def climb_stairs(n: int) -> int: """ Calculate the number of ways to climb a staircase with n steps, where you can either take 1 step or 2 steps at a time. Args: n (int): The number of steps in the staircase. R...
magic_evol_110k
83,688
Write a Python function to compute and return the cubed values of each distinct unit from a given set of numbers. The function should iterate through the list, compute the cube of each number, and store the results in a new list. The function should then return this list of cubed values. 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 compute_cubed_values(numbers: List[int]) -> List[int]: """ Computes the cubed values of each distinct unit from a given set of numbers. Args: numbers (List[int]): A list of integers for ...
magic_evol_110k
83,689
Write a Python function to convert a complex list of mixed data types (including strings, floats, booleans, and None) into a list of integers. The function should attempt to convert all numeric string representations to integers, convert boolean values to their integer equivalents, and replace all non-integer values wi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Union def convert_complex_list(lst: List[Union[str, float, bool, None]]) -> List[int]: """ Converts a complex list of mixed data types into a list of integers. The function attempts to convert all ...
magic_evol_110k
83,703
Write a Python function to find and return all prime numbers within a given range `[start, end]`. The function should use an efficient algorithm to determine if a number is prime. The code should start with: ```python from typing import List def find_primes_in_range(start: int, end: int) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_primes_in_range(start: int, end: int) -> List[int]: """ Find all prime numbers within the given range [start, end]. Args: start (int): The starting number of the range (inclusive). ...
magic_evol_110k
83,709
Write a Python function to implement the bubble sort algorithm for a given array of integers. The function should sort the array in ascending order. The code should start with: ```python from typing import List def bubble_sort(arr: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def bubble_sort(arr: List[int]) -> List[int]: """ Sorts the given array of integers using the bubble sort algorithm. Args: arr (List[int]): The array of integers to be sorted. Returns: ...
magic_evol_110k
83,711
Write a Python function to classify emails into two categories based on the content: "spam" or "regular". The function should identify spam emails by checking for specific phrases or words commonly found in spam messages. If any of these phrases or words are found in the email text, the email should be classified as "s...
Here is the Python code to solve the given problem in the markdown block: ```python def classify_email(email_text: str) -> str: """ Classify an email into 'spam' or 'regular' based on the presence of specific spam phrases. Args: email_text (str): The text content of the email to be classified. ...
magic_evol_110k
83,719
Write a Python function to generate a SQL query that fetches the top 3 books with the most reviews from a library database. The query should also fetch the average rating of each book and list them primarily from categories with the least book entries. Only consider books that have a review count of 10 or more. The que...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_top_books_query() -> str: """ Generates a SQL query to fetch the top 3 books with the most reviews from a library database. The query also fetches the average rating of each book and prioritizes categories with ...
magic_evol_110k
83,724
Write a Python function to verify if a list of numerical values contains only a single unique element. The function should handle exceptions for non-numeric inputs and empty lists. The function should return `True` if all elements in the list are the same, and `False` otherwise. If the list is empty or contains non-num...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def check_single_unique_element(lst: List[float]) -> bool: """ Verifies if a list of numerical values contains only a single unique element. Args: lst (List[float]): The list of numerical va...
magic_evol_110k
83,736
Write a Python function to calculate the cumulative count of elements in a nested multidimensional array structure. The array may contain numbers, strings, and other nested arrays of unknown depth. The function should correctly count all elements, including those within nested arrays. 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, Union def count_elements(arr: List[Union[int, str, List]]) -> int: """ Calculate the cumulative count of elements in a nested multidimensional array. Args: arr (List[Union[int, str, List]])...
magic_evol_110k
83,737
Write a Python function to intersperse a given delimiter between each element of a list of integers using recursion. The function should correctly handle the interspersion and avoid the flawed multi-level looping structure present in the original code. The function 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 intersperse_with_recursion(numbers: List[int], delimiter: int) -> List[int]: """ Intersperses a given delimiter between each element of a list of integers using recursion. Args: numbers ...
magic_evol_110k
83,739
Write a Python function to count the number of vowels in a given string, considering both uppercase and lowercase vowels, and excluding numbers and special characters. The function should be case-insensitive and should only count the vowels 'a', 'e', 'i', 'o', 'u'. The code should start with: ```python def count_vowel...
Here is the Python code to solve the given problem in the markdown block: ```python def count_vowels(s: str) -> int: """ Counts the number of vowels in the given string, considering both uppercase and lowercase vowels. Args: s (str): The input string in which to count the vowels. Returns: ...
magic_evol_110k
83,742
Write a Python function to normalize a list of words by converting each word to its lowercase form. Additionally, ensure that the function can handle an empty list and a list containing non-string elements by converting any non-string elements to strings before normalizing them. 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 normalize_wordlist(word_list: List[str]) -> List[str]: """ Normalizes a list of words by converting each word to its lowercase form. Non-string elements are converted to strings before normalizat...
magic_evol_110k
83,749
Write a Python function to retrieve the element at a specific ordinal position from a given numerical series. The ordinal position is defined as the position in the series where the first element is at position 1, the second element is at position 2, and so on. The function should handle cases where the position is out...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def get_element_at_ordinal_position(series: List[int], position: int) -> Optional[int]: """ Retrieves the element at a specific ordinal position from a given numerical series. Args: ...
magic_evol_110k
83,752
Write a Python function to determine if a given integer is a prime number. The function should return `True` if the number is prime and `False` otherwise. The function should handle edge cases such as negative numbers, 0, and 1, which are not prime numbers. The function should also be efficient for larger numbers by on...
Here is the Python code to solve the given problem in the markdown block: ```python def is_prime_number(number: int) -> bool: """ Determines if a given integer is a prime number. Args: number (int): The integer to check for primality. Returns: bool: True if the number is prime, False o...
magic_evol_110k
83,770
Write a Python function to generate the first `n` numbers in the Fibonacci sequence using an array data structure. The function should return the array containing the Fibonacci sequence. The code should start with: ```python from typing import List def generate_fibonacci(n: int) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_fibonacci(n: int) -> List[int]: """ Generate the first n numbers in the Fibonacci sequence. Args: n (int): The number of Fibonacci numbers to generate. Returns: Lis...
magic_evol_110k
83,778
Write a Python function to update a flag map based on the presence of a specific nucleotide sequence in a given list of nucleotides. The function should mark the positions in the flag map where the nucleotide sequence is found with `1` and leave the rest as `0`. 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 update_flag_map(nucleotides: List[str], sequence: str) -> List[int]: """ Updates a flag map based on the presence of a specific nucleotide sequence in a given list of nucleotides. Args: ...
magic_evol_110k
83,800
Write a Python function to calculate the minimum number of jumps required to reach a point (d, 0) from the origin (0, 0) in a 2D plane, given a fixed jump length. If the jump length is not a perfect divisor of the distance 'd', the function should return the minimum number of jumps required to reach or surpass the poin...
Here is the Python code to solve the given problem in the markdown block: ```python import math def min_jumps_to_reach(jump_length: float, d: float) -> int: """ Calculate the minimum number of jumps required to reach a point (d, 0) from the origin (0, 0) given a fixed jump length. If the jump length is not...
magic_evol_110k
83,802
Write a Python function to remove not just duplicates, but also tuples that contain any repeated element from a list of tuples. Each tuple contains a string and an integer. If any string or any integer appears more than once in the tuples of the list, all tuples containing them should be removed. The function should re...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def get_unique_data(data_collection: List[Tuple[str, int]]) -> List[Tuple[str, int]]: """ Removes tuples with repeated elements from a list of tuples. Args: data_collection (List[Tupl...
magic_evol_110k
83,809
Write a Python function to convert an integer within the range from zero to five inclusive into its corresponding textual representation. If the integer is outside this range, return "Invalid number". The function should start with: ```python def number_to_text(num: int) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python def number_to_text(num: int) -> str: """ Converts an integer within the range from zero to five inclusive into its corresponding textual representation. Args: num (int): The integer to be converted. Returns: ...
magic_evol_110k
83,829
Write a Python function to construct a tuple containing multiple elements, where each element is a string. The function should accept a list of strings as input and return a tuple containing these strings. The function should also ensure that the input list contains only strings and handle cases where the input list mi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def construct_string_tuple(strings: List[str]) -> Tuple[str, ...]: """ Constructs a tuple containing multiple elements, where each element is a string. Args: strings (List[str]): A li...
magic_evol_110k
83,839
Write a Python function to generate a Google Drive OAuth2 authorization URL for a given client ID and redirect URI. The function should return the authorization URL that users can visit to grant access to their Google Drive files. The URL should include the necessary query parameters such as `client_id`, `redirect_uri`...
Here is the Python code to solve the given problem in the markdown block: ```python from urllib.parse import urlencode def generate_google_drive_auth_url(client_id: str, redirect_uri: str) -> str: """ Generates a Google Drive OAuth2 authorization URL. Args: client_id (str): The client ID obtained ...
magic_evol_110k
83,848
Write a Python function to sort a list of integers in ascending order based on the digit length of the numbers. If two numbers have the same digit length, they should be sorted by their base ten (decimal) value. The function should handle both positive and negative 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 sort_by_digit_length(arr: List[int]) -> List[int]: """ Sorts a list of integers in ascending order based on the digit length of the numbers. If two numbers have the same digit length, they are so...
magic_evol_110k
83,859
Write a Python function to remove all the starting even numbers from a given list. The function should continue to remove the first element of the list as long as it is an even number. The function should return the modified list. The code should start with: ```python from typing import List def delete_starting_evens...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def delete_starting_evens(lst: List[int]) -> List[int]: """ Removes all starting even numbers from the given list. Args: lst (List[int]): The list from which to remove starting even numbers....
magic_evol_110k
83,874
Write a Python function to count the number of occurrences of a given word in an array of strings, considering case sensitivity and ensuring the target word has more than 3 characters. The function should return 0 if the target word has 3 or fewer characters. The code should start with: ```python from typing import Li...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_occurrences(words: List[str], target_word: str) -> int: """ Counts the number of occurrences of a given word in an array of strings, considering case sensitivity. Returns 0 if the target wo...
magic_evol_110k
83,883
Write a Python function to find the two array elements that contribute to the maximal combined numerical value. The function should have a time complexity better or equal to O(n log n). The code should start with: ```python from typing import List def find_max_combo(arr: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_max_combo(arr: List[int]) -> List[int]: """ Find the two array elements that contribute to the maximal combined numerical value. Args: arr (List[int]): The input array of integers. ...
magic_evol_110k
83,895
Write a Python function to iterate over a given list and return a new list containing each element from the original list, followed by its index. The function should handle lists of any length and type of elements. The code should start with: ```python from typing import List, Any def indexed_elements(array: List[Any...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def indexed_elements(array: List[Any]) -> List[tuple]: """ Returns a list of tuples where each tuple contains an element from the input list and its index. Args: array (List[Any]): The ...
magic_evol_110k
83,909
Write a Python function to classify three unique entities based on their characteristics using a decision tree model. Each entity is characterized by its shape, color, and size. The function should return a classification label for each entity based on the decision tree logic. The entities are: 1. Entity 1: spherical,...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def classify_entities(entities: List[Dict[str, str]]) -> List[str]: """ Classify entities based on their shape, color, and size using a decision tree model. Args: entities (List[Dict[s...
magic_evol_110k
83,921
Write a Python function to find the intersection of two lists without using built-in functions like `set.intersection` or list comprehensions. The function should iterate through both lists to find common elements and return a new list containing these common 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 def list_intersection(lst1: List[int], lst2: List[int]) -> List[int]: """ Find the intersection of two lists without using built-in functions. Args: lst1 (List[int]): The first list of integ...
magic_evol_110k
83,922
Write a Python function to clean a given text by removing all superfluous white spaces and replacing them with a single space. The function should also handle leading and trailing white spaces. The code should start with: ```python import re def clean_text(text: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python import re def clean_text(text: str) -> str: """ Cleans the given text by replacing all sequences of superfluous white spaces with a single space and removing any leading or trailing spaces. Args: text (str): Th...
magic_evol_110k
83,925
Write a Python function to find all instances of a given string `y` within a nested list `info`. The function should return a list of tuples where each tuple represents the index positions (row and index) of the occurrences of `y` in the nested list. If `y` appears multiple times in a single nested list, the tuples sho...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_str_positions(info: List[List[str]], y: str) -> List[Tuple[int, int]]: """ Find all instances of the string `y` in the nested list `info` and return their positions as a list of tuples. ...
magic_evol_110k
83,926
Write a Python decorator that checks if a value is negative before passing it to the decorated function. If the value is negative, the decorator should raise a `ValueError`. Additionally, the decorator should track and print the number of times each decorated function is called. The code should start with: ```python d...
Here is the Python code to solve the given problem in the markdown block: ```python def check_negative(func): """ A decorator that checks if a value is negative before passing it to the decorated function. If the value is negative, it raises a ValueError. Additionally, it tracks and prints the number of...
magic_evol_110k
83,932
Write a Python function to determine if two given strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. The function should be case-insensitive and should ignore spaces and punctuation. T...
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. Args: str1 (str): The first string to compare. str2 (str): The second string to compare. Re...
magic_evol_110k
83,936
Write a Python function to find the maximum number in a given list of integers and determine if this maximum number is a prime number. The function should return a tuple containing the maximum number and a boolean indicating whether it is a prime number. The code should start with: ```python from typing import List, Tu...
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 given number is a prime number. Args: n (int): The number to check for primality. Returns: bool: True if the number is prime,...
magic_evol_110k
83,945
Write a Python function to process a list of strings in a specific order, ensuring that each string is processed exactly once and in the order they appear in the list. The function should return a new list where each string is transformed by appending its index and the total number of elements in the list. The function...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def process_strings(data: List[str]) -> List[str]: """ Process a list of strings by appending each string with its index and the total number of elements in the list. Args: data (List[str]):...
magic_evol_110k
83,953
Write a Python function to perform a ternary search for a specific element in a pre-sorted numerical array. The function should return the index of the element if it is found, otherwise it should return -1. The code should start with: ```python from typing import List def ternary_search(arr: List[int], key: int) -> in...
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], key: int) -> int: """ Perform a ternary search to find the index of a specific element in a pre-sorted numerical array. Args: arr (List[int]): The pre-sort...
magic_evol_110k
83,964
Write a Python function to create and return a pandas DataFrame from a given dictionary. The dictionary will have two keys: 'State' and 'Zipcode', each containing a list of corresponding values. The function should ensure that the DataFrame is created correctly and returned. The code should start with: ```python impor...
Here is the Python code to solve the given problem in the markdown block: ```python import pandas as pd from typing import Dict, List def create_dataframe(data: Dict[str, List[str]]) -> pd.DataFrame: """ Create a pandas DataFrame from a given dictionary with 'State' and 'Zipcode' keys. Args: data ...
magic_evol_110k
83,965
Write a Python function to filter out integers from a given list that exceed a specified limit. The function should return a new list containing only the integers that are less than or equal to the specified limit. The code should start with: ```python from typing import List def filter_numbers(numbers: List[int], lim...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_numbers(numbers: List[int], limit: int) -> List[int]: """ Filters out integers from the given list that exceed the specified limit. Args: numbers (List[int]): The list of integers...
magic_evol_110k
83,967
Write a Python function to perform a series of operations on a 3D integer array. The operations include transposing the layers of the array, reversing the order of elements within each layer, and then sorting each layer in ascending order. The function should be optimized to reduce the time complexity to less than O(n^...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def transform_3d_array(array_3d: List[List[List[int]]]) -> List[List[List[int]]]: """ Transforms a 3D integer array by transposing its layers, reversing the order of elements within each layer, and t...
magic_evol_110k
83,991
Write a Python function to correct and validate a given JSON object representing a person's profile data. The JSON object may contain syntax errors and missing attributes. The function should: 1. Correct the syntax of the JSON object by ensuring all property names and string values are enclosed in double quotes. 2. Ens...
Here is the Python code to solve the given problem in the markdown block: ```python import json def correct_and_validate_profile(profile_json: str) -> str: """ Corrects the syntax of a given JSON object representing a person's profile data and validates it. Args: profile_json (str): The JSON strin...
magic_evol_110k
84,029
Write a Python function to calculate and return the first `n` Fibonacci numbers. The function should be efficient and handle edge cases such as `n` being 0 or 1. The code should start with: ```python from typing import List def generate_fibonacci(n: int) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_fibonacci(n: int) -> List[int]: """ Generate the first n Fibonacci numbers. Args: n (int): The number of Fibonacci numbers to generate. Returns: List[int]: A list c...
magic_evol_110k
84,038
Write a Python function to calculate the Euclidean distance between corresponding pairs of points in two numerical arrays and store the results in a new array. Additionally, implement boundary tests to handle any possible faults in the data points of the arrays, such as non-numerical values or missing data points, with...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def euclidean_distance(a: List[float], b: List[float]) -> List[float]: """ Calculate the Euclidean distance between corresponding pairs of points in two numerical arrays. Args: a...
magic_evol_110k
84,056
Write a Python function to perform a depth-first search (DFS) on a given graph without using recursion. The function should manage the stack manually and return the set of visited nodes. The graph is represented as an adjacency list where each key is a node and the value is a set of connected nodes. The code should st...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Set def dfs_iterative(graph: Dict[str, Set[str]], start: str) -> Set[str]: """ Perform a depth-first search (DFS) on a graph represented as an adjacency list. Args: graph (Dict[str, Set[str...
magic_evol_110k
84,073
Write a Python function to generate a random character within a given range of characters. The function should accept two parameters: `start` and `end`, which are characters representing the inclusive range of characters to choose from. The function should return a single random character from this range. The code sho...
Here is the Python code to solve the given problem in the markdown block: ```python import random def generate_random_char(start: str, end: str) -> str: """ Generates a random character within the given inclusive range of characters. Args: start (str): The starting character of the range (inclusiv...
magic_evol_110k
84,100
Write a Python function to calculate the occurrence rate of each distinct term in a given English phrase. The function should return a dictionary where the keys are the distinct terms and the values are their respective occurrence counts. The function should handle case insensitivity by converting all terms to lowercas...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def word_occurrence_rate(sentence: str) -> Dict[str, int]: """ Calculate the occurrence rate of each distinct term in a given English phrase. Args: sentence (str): The input sentence from wh...
magic_evol_110k
84,108
Write a Python function to find the intersection of three sorted arrays. The function should return a sorted list of integers that are present in all three input arrays. The input arrays are guaranteed to be sorted in strictly ascending order. The code should start with: ```python from typing import List def find_int...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_intersection_of_three_arrays(arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: """ Find the intersection of three sorted arrays. Args: arr1 (List[int]): The first sor...
magic_evol_110k
84,109
Write a Python function to merge two sorted lists into a new sorted list containing the unique elements of both lists without using built-in functions or libraries. The function should start with: ```python from typing import List def merge_sorted_unique(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_unique(list1: List[int], list2: List[int]) -> List[int]: """ Merges two sorted lists into a new sorted list containing the unique elements of both lists. Args: list1 (List[i...
magic_evol_110k
84,120
Write a Python function to calculate the new height of a photograph after it has been proportionally enlarged, given the original dimensions and the new width. The function should return the new height as a floating-point number. The code should start with: ```python def calculate_new_height(original_width: float, ori...
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_new_height(original_width: float, original_height: float, new_width: float) -> float: """ Calculate the new height of a photograph after it has been proportionally enlarged. Args: original_width (float...
magic_evol_110k
84,148
Write a Python function to determine if all the given textual elements (lexemes) in a collection form anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. The function should be case-insensitive and...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import re def are_all_anagrams(lexeme_collection: List[str]) -> bool: """ Determines if all the given textual elements (lexemes) in a collection form anagrams of each other. Args: lexeme_col...
magic_evol_110k
84,153
Write a Python function to generate a response that contains a list of words sorted in increasing alphabetical order. The function should take a list of words as input and return a string where the words are joined by a comma and a space. The code should start with: ```python from typing import List def generate_sort...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_sorted_response(words: List[str]) -> str: """ Generates a response string containing the words from the input list sorted in increasing alphabetical order. Args: words (List[str...
magic_evol_110k
84,159
Write a Python function to simulate the booking process in a hotel booking system. The function should handle the following operations: 1. **Searching for available rooms**: Given a location, check-in date, check-out date, and room type, return a list of available rooms. 2. **Booking a room**: Given a room ID, check-in...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Tuple from datetime import datetime def search_available_rooms(rooms: List[Dict], location: str, check_in: datetime, check_out: datetime, room_type: str) -> List[Dict]: """ Search for available ro...
magic_evol_110k
84,180
Write a Python function to simulate a bank account balance based on a list of operations. The function should return `True` if the account balance is never negative during the operations, and the final balance is zero. Otherwise, it should return `False`. Each operation is a tuple where the first element is the type of...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Union def below_zero(operations: List[Tuple[str, Union[int, str]]], case_insensitive: bool = False) -> bool: """ Simulate a bank account balance based on a list of operations and check if the bal...
magic_evol_110k
84,181
Write a Python function to find the largest prime factor of a given number, which can be a positive, negative, or a decimal number. The function should handle negative values by converting them to positive and should accurately process floating-point numbers by converting them to integers. The function should also ensu...
Here is the Python code to solve the given problem in the markdown block: ```python def accurate_largest_prime_factor(n: float) -> int: """ Return the largest prime factor of a positive, negative, or a decimal number. Args: n (float): The number for which to find the largest prime factor. Retu...
magic_evol_110k
84,188
Write a Python function to find the length and the longest common substring between two given strings. The function should run with a time complexity of O(N*M), where N and M are the lengths of the two strings respectively. The function should return both the length of the longest common substring and the substring its...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple def longest_common_substring_with_length(s1: str, s2: str) -> Tuple[int, str]: """ Finds the length and the longest common substring between two given strings. Args: s1 (str): The first str...
magic_evol_110k
84,199
Write a Python function to find the length of the longest increasing subsequence (LIS) in a given numerical array. The function should efficiently compute the LIS using dynamic programming. The code should start with: ```python from typing import List def longest_increasing_subsequence(arr: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def longest_increasing_subsequence(arr: List[int]) -> int: """ Calculate the length of the longest increasing subsequence in a given numerical array. Args: arr (List[int]): The input array o...
magic_evol_110k
84,203
Write a Python function to invert the elements of an integer array such that the initial element transposes positions with the final one, and reciprocally for all respective elements. The function should start with: ```python from typing import List def invert_array_elements(arr: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def invert_array_elements(arr: List[int]) -> List[int]: """ Inverts the elements of an integer array such that the initial element transposes positions with the final one, and reciprocally for all respec...
magic_evol_110k
84,212
Write a Python function to combine two lists such that their elements are alternately placed. If one list is longer than the other, the remaining elements of the longer list should be appended to the end of the combined list. The code should start with: ```python from typing import List def combine_alternately(list1:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List from itertools import zip_longest def combine_alternately(list1: List[int], list2: List[int]) -> List[int]: """ Combines two lists such that their elements are alternately placed. If one list is long...
magic_evol_110k
84,223
Write a Python function to find the largest number in a given array without using the built-in `max()` function. The function should iterate through the array and keep track of the largest number encountered. The code should start with: ```python from typing import List def find_largest_num(array: List[int]) -> int: ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_largest_num(array: List[int]) -> int: """ Find the largest number in a given array without using the built-in max() function. Args: array (List[int]): The array of integers from whi...
magic_evol_110k
84,239
Write a Python function to generate a list of `n` distinct random capital letters. The function should handle potential exceptions and provide suitable error messages when exceptions occur. Additionally, provide a piece of erroneous code and explain why it is incorrect or incapable. 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 import random import string def generate_distinct_random_letters(n: int) -> List[str]: """ Generates a list of `n` distinct random capital letters. Args: n (int): The number of distinct rand...
magic_evol_110k
84,249
Write a Python function to determine the maximum profit that can be obtained by buying and selling a stock once, given a list of daily stock prices. The function should ensure that the stock is bought before it is sold. The code should start with: ```python from typing import List def max_profit_from_stock(stock_price...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def max_profit_from_stock(stock_prices: List[int]) -> int: """ Calculate the maximum profit that can be obtained by buying and selling a stock once, given a list of daily stock prices. The stock must...
magic_evol_110k
84,276
Write a Python function to append a new element to an existing array and return the updated array. The function should handle the case where the input array is `None` by initializing it as an empty list before appending the new element. The code should start with: ```python from typing import List, Optional def append...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def append_to_array(array: Optional[List[int]], new_element: int) -> List[int]: """ Appends a new element to an existing array and returns the updated array. If the input array is None, it ...
magic_evol_110k
84,286
Write a Python function to reverse the order of words in a given string without using any in-built functions for string manipulation (e.g., `split`, `join`, `reverse`). The function should handle multiple spaces between words and leading/trailing spaces. The code should start with: ```python def reverse_words_in_strin...
Here is the Python code to solve the given problem in the markdown block: ```python def reverse_words_in_string(input_string: str) -> str: """ Reverses the order of words in a given string without using any in-built functions for string manipulation. Args: input_string (str): The input string conta...
magic_evol_110k
84,289
Write a Python function to determine if the second string, or any of its cyclical permutations, exist as consecutive subsequences within the first string. The function should ignore case and non-alphanumeric elements. The code should start with: ```python import re def cycled_pattern_search(a: str, b: str) -> bool: ``...
Here is the Python code to solve the given problem in the markdown block: ```python import re def cycled_pattern_search(a: str, b: str) -> bool: """ Determine if the second string, or any of its cyclical permutations, exist as consecutive subsequences within the first string. The function ignores case and ...
magic_evol_110k
84,300
Write a Python function to filter and return a list of prime numbers from a given list of integers. The function should use a helper function to determine if a number is prime. The code should start with: ```python from typing import List def is_prime(n: int) -> bool: # Helper function to determine if a number is ...
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: """ Helper function to determine if a number is prime. Args: n (int): The number to check for primality. Returns: bool: True if the number is prime...
magic_evol_110k
84,301
Write a Python function to check if a given directory exists, calculate the number of files and subdirectories within it, and display the result along with the directory path. Additionally, if the directory contains any file with a specific file extension (such as ".txt"), count the number of such files and display the...
Here is the Python code to solve the given problem in the markdown block: ```python import os def directory_info(dir_path: str, file_extension: str = ".txt") -> None: """ Check if a given directory exists, calculate the number of files and subdirectories within it, and display the result along with the dir...
magic_evol_110k
84,302
Write a Python function to detect and nullify any duplicate rows in a given matrix. A duplicate row is defined as a row that has the same elements as another row in the matrix. Nullifying a row means replacing all its elements with zeros. The function should return the modified matrix. The code should start with: ```p...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def nullify_duplicate_rows(matrix: List[List[int]]) -> List[List[int]]: """ Detects and nullifies any duplicate rows in the given matrix. Args: matrix (List[List[int]]): The matrix to proces...
magic_evol_110k
84,315
Write a Python function to validate US postal zip codes using regular expressions. The function should accurately differentiate between valid five-digit basic format and valid nine-digit 'ZIP+4' format, while excluding invalid zip codes. The function should return `True` if the zip code is valid and `False` otherwise. ...
Here is the Python code to solve the given problem in the markdown block: ```python import re def is_valid_us_zip(code: str) -> bool: """ Validates a US postal zip code using regular expressions. Args: code (str): The zip code to validate. Returns: bool: True if the zip code is valid,...
magic_evol_110k
84,321
Write a Python function to sort a dictionary of dwarfs' names and their ages in ascending order based on their ages. If two dwarfs have the same age, sort them alphabetically by their names. The function should return the sorted dictionary. The code should start with: ```python from typing import Dict def sort_dwarfs...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def sort_dwarfs_by_age(dwarfs: Dict[str, int]) -> Dict[str, int]: """ Sorts a dictionary of dwarfs' names and their ages in ascending order based on their ages. If two dwarfs have the same age, they ...
magic_evol_110k
84,331
Write a Python function to count the frequency of a specific character in a given string. The function should be case-sensitive, meaning it should distinguish between uppercase and lowercase characters. The code should start with: ```python def count_character_frequency(text: str, character: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def count_character_frequency(text: str, character: str) -> int: """ Counts the frequency of a specific character in a given string. Args: text (str): The string in which to count the character. character (s...
magic_evol_110k
84,339
Write a Python function to determine whether one string is a subsequence of another. A string is considered a subsequence of another if all characters of the first string appear in the same order within the second string, but not necessarily consecutively. The function should start with: ```python def is_subsequence(s...
Here is the Python code to solve the given problem in the markdown block: ```python def is_subsequence(string1: str, string2: str) -> bool: """ Determines whether string1 is a subsequence of string2. Args: string1 (str): The string to check if it is a subsequence. string2 (str): The string ...
magic_evol_110k
84,351
Write a Python function to determine the Greatest Common Divisor (GCD) of two provided 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
84,366
Write a Python function to perform polynomial addition for two polynomials represented as dictionaries. Each dictionary maps the exponent to the coefficient for a single variable polynomial. The function should handle polynomials with negative exponents and return the resulting polynomial as a dictionary. The code sho...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def add_polynomials(poly1: Dict[int, float], poly2: Dict[int, float]) -> Dict[int, float]: """ Adds two polynomials represented as dictionaries. Args: poly1 (Dict[int, float]): The first pol...
magic_evol_110k
84,369
Write a Python function to calculate the area of a circle given its radius, and format the output to display the area with exactly two decimal places. The function should take the radius as an input and return the formatted area as a string. The code should start with: ```python import math def calculate_circle_area(...
Here is the Python code to solve the given problem in the markdown block: ```python import math def calculate_circle_area(radius: float) -> str: """ Calculate the area of a circle given its radius and format the output to two decimal places. Args: radius (float): The radius of the circle. Ret...
magic_evol_110k
84,373
Write a Python function to print the elements of a given array at specified indices. The function should take two arguments: the array and a list of indices. The function should print the elements at the specified indices in the order they appear in the list of indices. The code should start with: ```python from typin...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def print_specific_elements(arr: List[int], indices: List[int]) -> None: """ Prints the elements of the given array at the specified indices. Args: arr (List[int]): The array from which to p...
magic_evol_110k
84,389
Write a Python function that accepts an alphanumeric string as input and returns a tuple containing three elements: the sum of all the individual digits present in the string, the largest digit, and the smallest digit. The function should handle large alphanumeric strings efficiently and provide robust error handling f...
Here is the Python code to solve the given problem in the markdown block: ```python def sum_digits_and_extremes(string: str) -> tuple: """ Extracts all digits from the given alphanumeric string, calculates their sum, and finds the largest and smallest digits. Args: string (str): The alphanumeric st...
magic_evol_110k
84,401
Write a Python function to calculate the arithmetic mean of a given list of numbers. The function should handle lists of any length, including empty lists, and return `None` for an empty list. The code should start with: ```python from typing import List, Optional def calculate_mean(numbers: List[float]) -> Optional[f...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def calculate_mean(numbers: List[float]) -> Optional[float]: """ Calculate the arithmetic mean of a given list of numbers. Args: numbers (List[float]): The list of numbers for whic...
magic_evol_110k
84,410
Write a Python function to calculate the factorial of a given number using memoization to improve efficiency and computation time. The function should be based on a recursive routine and should store previously computed factorial values in a dictionary to avoid redundant calculations. The code should start with: ```pyt...
Here is the Python code to solve the given problem in the markdown block: ```python def factorial_memo(n: int, memo: dict = None) -> int: """ Calculate the factorial of a given number using memoization to improve efficiency. Args: n (int): The number for which to calculate the factorial. me...
magic_evol_110k
84,411
Write a Python function to convert a list of tuples into a dictionary. Each tuple contains an individual's name, occupation, birthday, and hobby. The function should handle cases where some tuples may be missing one or more elements and should set default values for missing elements. The function should start with: ``...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict, Any def convert_to_dict(people_list: List[Tuple[str, str, str, str]], default_value: Any = None) -> Dict[str, Dict[str, Any]]: """ Converts a list of tuples into a dictionary. Each tuple co...
magic_evol_110k
84,439
Write a Python function to detect and filter out prime numbers from a given list of numbers that contains both integers and floating point values. The function should stop checking for primes once it encounters an erroneous piece of code in the list rather than producing an error message. Additionally, the function sho...
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 a given integer is a prime number. Args: n (int): The number to check for primality. Returns: bool: True if the number is prime, False...
magic_evol_110k
84,463
Write a Python function to filter out strings from a list that start with a specific prefix and return the modified list. The function should handle edge cases such as an empty list or an empty prefix. The code should start with: ```python from typing import List def filter_strings_by_prefix(strings: List[str], prefix...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_strings_by_prefix(strings: List[str], prefix: str) -> List[str]: """ Filters out strings from the input list that start with the specified prefix and returns the modified list. Args: ...
magic_evol_110k
84,465
Write a Python function to determine if it's possible to divide a given number of individuals into two distinct groups such that no two individuals who dislike each other are placed in the same group. The function should take the number of individuals `N` and a list of dislikes `dislikes` where each entry is a pair of ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def possible_bipartition(N: int, dislikes: List[List[int]]) -> bool: """ Determine if it's possible to divide N individuals into two groups such that no two individuals who dislike each other are in the ...
magic_evol_110k
84,484
Write a Python function to convert a list of tuples into a dictionary and then display each key-value pair in the dictionary. The function should handle any list of tuples where each tuple contains exactly two elements: a key and a value. The code should start with: ```python from typing import List, Tuple, Dict def c...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Dict def convert_and_display(tuples_list: List[Tuple[str, str]]) -> None: """ Converts a list of tuples into a dictionary and displays each key-value pair. Args: tuples_list (List[Tu...
magic_evol_110k
84,495
Write a Python function that takes a list of student dictionaries as input and returns a dictionary where each key is a grade, and the value is a list of all students who have that grade, sorted alphabetically. Additionally, ensure that the returned dictionary keys are sorted in alphabetical order. The function should ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def sort_students_by_grade(students: List[Dict[str, str]]) -> Dict[str, List[str]]: """ Sorts students by their grades and returns a dictionary where each key is a grade, and the value is a lis...
magic_evol_110k
84,502
Write a Python function to count the number of index pairs (i, j) where the elements at these indices in two given sequences A and B are equal. The sequences A and B may have different lengths and can contain repetitive elements. The function should efficiently handle sequences with up to 10^6 elements. The code shoul...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_common_pairs(A: List[int], B: List[int]) -> int: """ Count the number of index pairs (i, j) where A[i] == B[j]. Args: A (List[int]): The first sequence of integers. B (List...
magic_evol_110k
84,503
Write a Python function to display distinct integer entities with allocated values in a matrix-like formation. The function should take a list of integers and a number of columns as input and print the integers in a formatted matrix. The matrix should be filled row by row, and if the last row is not completely filled, ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def display_matrix(numbers: List[int], num_columns: int) -> None: """ Displays a list of integers in a matrix-like formation with the specified number of columns. Args: numbers (List[int]): ...
magic_evol_110k
84,508
Write a Python function to create a three-level deep hierarchical dictionary using three arrays. The first array values will be the first key, the second array values will be the second key, and the third array values will be the assigned values. Each value from each array must be used exactly once and only once. The f...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def create_hierarchical_dict(l1: List[str], l2: List[int], l3: List[int]) -> Dict[str, Dict[int, int]]: """ Creates a three-level deep hierarchical dictionary using three arrays. Args: ...
magic_evol_110k
84,515
Write a Python function that converts a given string into its corresponding lowercase counterpart while ensuring that the string contains only alphabetical characters. If the input string contains any non-alphabetical characters, they should be removed before the conversion. The function should return the cleaned and c...
Here is the Python code to solve the given problem in the markdown block: ```python def clean_convert_string(input_string: str) -> str: """ Converts a given string into its corresponding lowercase counterpart while ensuring that the string contains only alphabetical characters. Non-alphabetical characters ...
magic_evol_110k
84,527
Write a Python function to convert all punctuation marks in a given piece of text into hyphens. The function should be efficient and handle larger texts without performance issues. The code should start with: ```python import string def convert_punctuation_to_hyphens(text: str) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python import string def convert_punctuation_to_hyphens(text: str) -> str: """ Converts all punctuation marks in the given text into hyphens. Args: text (str): The input text containing punctuation marks. Returns: ...
magic_evol_110k
84,529
Write a Python function to generate a list of ten unique sequences of random, non-repeating alphanumeric characters. Each sequence should increase in length from 5 to 14 characters. The function should ensure that each full sequence is unique, not just the individual characters within a sequence. The function should st...
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_sequences() -> List[str]: """ Generates a list of ten unique sequences of random, non-repeating alphanumeric characters. Each sequence increases in len...
magic_evol_110k
84,534
Write a Python function to update the population of a metropolis in a given dictionary. If the metropolis is not already in the dictionary, add it with the specified population. The function should return the updated dictionary. The code should start with: ```python from typing import Dict, Union def update_populatio...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Union def update_population(metropolis_population: Dict[str, float], city: str, population: float) -> Dict[str, float]: """ Updates the population of a metropolis in the given dictionary. If the metropo...
magic_evol_110k
84,535
Write a Python function to create a 3D cubic tensor of a given size, where each element is initialized to a specified value. The function should return the created tensor. The code should start with: ```python import numpy as np def create_3d_tensor(size: int, value: int) -> np.ndarray: ```
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np def create_3d_tensor(size: int, value: int) -> np.ndarray: """ Create a 3D cubic tensor of the given size, where each element is initialized to the specified value. Args: size (int): The size of ...
magic_evol_110k
84,547
Write a Python function to sort an array of floating point numbers from largest to smallest without using any in-built Python sorting functions. Additionally, implement error handling for non-float elements. The function should print an error message for each non-float element detected and exclude it from the sorting p...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_floats_descending(nums: List[float]) -> List[float]: """ Sorts an array of floating point numbers from largest to smallest without using any in-built Python sorting functions. Non-float elem...
magic_evol_110k
84,550
Write a Python function to integrate an array of distinct lexical elements into a single, uninterrupted text string. Each word in the array should be separated by a comma and a space character. The function should handle an empty list by returning an empty string. 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 def integrate_into_string(lst: List[str]) -> str: """ Integrates an array of distinct lexical elements into a single, uninterrupted text string. Each word in the array is separated by a comma and a s...
magic_evol_110k
84,561
Write a Python function to simulate the behavior of calling a Rake task multiple times from a Ruby script. The function should accept a list of task names and their corresponding arguments, and then simulate the execution of each task. The function should print out the task name and its arguments as if they were being ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def simulate_rake_tasks(tasks: List[Tuple[str, str]]) -> None: """ Simulates the execution of multiple Rake tasks by printing the task names and their arguments. Args: tasks (List[Tup...
magic_evol_110k
84,566
Write a Python function to flatten a given two-dimensional matrix into a one-dimensional list. The matrix is composed of integer elements. The function should handle matrices of varying sizes, including empty matrices. The code should start with: ```python from typing import List def flatten_matrix(matrix: List[List[i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def flatten_matrix(matrix: List[List[int]]) -> List[int]: """ Flattens a given two-dimensional matrix into a one-dimensional list. Args: matrix (List[List[int]]): A two-dimensional matrix co...
magic_evol_110k
84,571
Write a Python function to calculate the cumulative sum of all integers in a given list. The function should handle lists of any length, including empty lists. The code should start with: ```python from typing import List def calculate_cumulative_sum(array: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_cumulative_sum(array: List[int]) -> int: """ Calculate the cumulative sum of all integers in the given list. Args: array (List[int]): The list of integers for which to calculat...
magic_evol_110k
84,574
Write a Python function to calculate the cumulative total of the harmonic sequence from 1/1 to 1/N. The function should handle invalid input and ensure that the calculation is performed efficiently. The code should start with: ```python def harmonic_sequence_sum(N: int) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python def harmonic_sequence_sum(N: int) -> float: """ Calculate the cumulative total of the harmonic sequence from 1/1 to 1/N. Args: N (int): The number of terms in the harmonic sequence to sum. Returns: floa...
magic_evol_110k
84,580
Write a Python function to convert a mixed number into an improper fraction. A mixed number is represented by a whole number and a proper fraction (where the numerator is less than the denominator). The function should return the improper fraction as a tuple of two integers: the numerator and the denominator. The code...
Here is the Python code to solve the given problem in the markdown block: ```python def convert_mixed_to_improper(whole: int, numerator: int, denominator: int) -> tuple: """ Converts a mixed number into an improper fraction. Args: whole (int): The whole number part of the mixed number. nume...