source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
code_exercise_27k
27,162
Write a Python function to determine if two given strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. The function should ignore case and whitespace. The code should start with: ```pyt...
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...
code_exercise_27k
27,163
Write a Python function to find the intersection of two given lists, ensuring that the result contains only unique elements and is sorted in ascending order. The function should handle lists with duplicate elements and return a new list with the common elements. 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 find_intersection(list1: List[int], list2: List[int]) -> List[int]: """ Find the intersection of two given lists, ensuring the result contains only unique elements and is sorted in ascending order. ...
code_exercise_27k
27,164
Write a Python function to remove all duplicate elements from a given list while preserving the order of the first occurrence of each element. The function should return a new list with all duplicate elements removed. The code should start with: ```python from typing import List def remove_duplicates_preserve_order(ls...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_duplicates_preserve_order(lst: List) -> List: """ Removes all duplicate elements from a given list while preserving the order of the first occurrence of each element. Args: lst (l...
code_exercise_27k
27,166
Write a Python function to implement the Binary Search algorithm. The function should take a sorted list of integers and a target integer as input, and return the index of the target value in the list if it is found. If the target value is not found, the function should return -1. The code should start with: ```python...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def binary_search(arr: List[int], target: int) -> int: """ Perform binary search on a sorted array to find the target value. Args: arr (List[int]): A sorted list of integers. target ...
code_exercise_27k
27,168
Write a Python function to determine if a given number is a perfect square. A perfect square is a number that can be expressed as the square of an integer. The function should use a binary search approach to efficiently determine if the number is a perfect square. The code should start with: ```python def is_perfect_s...
Here is the Python code to solve the given problem in the markdown block: ```python def is_perfect_square(num: int) -> bool: """ Determine if a given number is a perfect square using a binary search approach. Args: num (int): The number to be checked. Returns: bool: True if the number ...
code_exercise_27k
27,169
Write a Python function to find the Greatest Common Divisor (GCD) of two given numbers using the Euclidean algorithm. The function should handle only positive integers and should not raise any exceptions. The code should start with: ```python def gcd(num1: int, num2: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def gcd(num1: int, num2: int) -> int: """ Calculate the Greatest Common Divisor (GCD) of two positive integers using the Euclidean algorithm. Args: num1 (int): The first positive integer. num2 (int): The sec...
code_exercise_27k
27,170
Write a Python function to implement the Merge Sort algorithm for sorting a list. The function should recursively divide the list into halves until each sublist contains only one element, and then merge the sorted sublists back together. The code should start with: ```python from typing import List def merge_sort(arr:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def merge_sort(arr: List[int]) -> List[int]: """ Sorts a list using the Merge Sort algorithm. Args: arr (List[int]): The unsorted list of integers. Returns: List[int]: The sorte...
code_exercise_27k
27,172
Write a Python function to check if a given string contains a valid expression of parentheses, brackets, and braces. The function should ensure that each opening symbol has a corresponding closing symbol and that they are properly nested. The code should start with: ```python def is_valid_expression(input_string: str)...
Here is the Python code to solve the given problem in the markdown block: ```python def is_valid_expression(input_string: str) -> bool: """ Check if a given string contains a valid expression of parentheses, brackets, and braces. Args: input_string (str): The string to be checked. Returns: ...
code_exercise_27k
27,174
Write a Python function to implement the Quick Sort algorithm for sorting a list of integers. The function should be able to handle lists of varying lengths, including empty lists and lists with duplicate elements. The function should return a new list with elements sorted in ascending order. The code should start wit...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def quick_sort(arr: List[int]) -> List[int]: """ Sorts a list of integers using the Quick Sort algorithm. Args: arr (List[int]): The list of integers to be sorted. Returns: List...
code_exercise_27k
27,183
Write a Python function to find the k-th largest element in a given list of integers. The function should efficiently handle cases where the list is empty or k is out of bounds. The code should start with: ```python from typing import List, Optional def find_kth_largest_element(lst: List[int], k: int) -> Optional[int...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional def find_kth_largest_element(lst: List[int], k: int) -> Optional[int]: """ Find the k-th largest element in a list of integers. Args: lst (List[int]): The list of integers from whi...
code_exercise_27k
27,185
Write a Python function to swap the values of two variables without using a temporary variable. The function should take two arguments and return a tuple containing the swapped values. The code should start with: ```python def swap_variables(a: int, b: int) -> tuple: ```
Here is the Python code to solve the given problem in the markdown block: ```python def swap_variables(a: int, b: int) -> tuple: """ Swaps the values of two variables without using a temporary variable. Args: a (int): The first variable. b (int): The second variable. Returns: t...
code_exercise_27k
27,186
Write a Python function to generate a list of all prime numbers between two given numbers, inclusive. The function should efficiently determine if a number is prime and return the list of primes within the specified range. The code should start with: ```python from typing import List def generate_prime_numbers(start:...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import math def generate_prime_numbers(start: int, end: int) -> List[int]: """ Generate a list of prime numbers between the given start and end numbers, inclusive. Args: start (int): The sta...
code_exercise_27k
27,188
Write a Python function to sort a list of strings in descending order based on the length of the strings. If two strings have the same length, they should be sorted in ascending order based on their lexicographical order. The code should start with: ```python from typing import List def sort_strings_by_length(strings...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def sort_strings_by_length(strings: List[str]) -> List[str]: """ Sorts the given list of strings in descending order based on the length of the strings. If two strings have the same length, they ar...
code_exercise_27k
27,189
Write a Python function to find the second-largest element in a given list of integers. If the list has fewer than two elements, raise a `ValueError`. If there is no distinct second-largest element (i.e., all elements are the same), raise a `ValueError`. 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 find_second_largest(nums: List[int]) -> int: """ Find the second-largest element in a list of integers. Args: nums (List[int]): A list of integers. Returns: int: The second-...
code_exercise_27k
27,190
Write a Python function to determine if two given strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. The function should ignore case and spaces. The code should start with: ```python ...
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. str2 (str): The second string. Returns: bool: T...
code_exercise_27k
27,196
Write a Python function to implement a binary search algorithm that finds the first occurrence of a target value in a sorted array. If the target value is not found, return -1. The function should handle duplicate values by returning the index of the first occurrence. 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 binary_search_first_occurrence(arr: List[int], target: int) -> int: """ Perform binary search on a sorted array to find the first occurrence of the target value. Args: arr (List[int]...
code_exercise_27k
27,199
Write a Python function to find the longest common prefix among a given set of strings. The function should return an empty string if there is no common prefix. The code should start with: ```python from typing import List def longest_common_prefix(strings: List[str]) -> str: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def longest_common_prefix(strings: List[str]) -> str: """ Finds the longest common prefix among a given set of strings. Args: strings (List[str]): A list of strings. Returns: st...
code_exercise_27k
27,201
Write a Python function to calculate the average of a list of numbers. The function should handle empty lists by returning 0.0 and should raise a `TypeError` if the input is not a list of numbers. The code should start with: ```python from typing import List def calculate_average(numbers: List[float]) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def calculate_average(numbers: List[float]) -> float: """ Calculate the average of a list of numbers. This function takes a list of numbers as input and calculates their average. If the list is ...
code_exercise_27k
27,203
Write a Python function to count the number of vowels in a given string, considering both uppercase and lowercase vowels. The function should be case-insensitive and should return the total count of vowels in the string. The code should start with: ```python def count_vowels(string: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def count_vowels(string: str) -> int: """ Counts the number of vowels in a given string, considering both uppercase and lowercase vowels. Args: string (str): The input string in which to count the vowels. Retur...
code_exercise_27k
27,206
Write a Python function to sort a dictionary by its values in descending order. If two or more keys have the same value, sort these keys by their natural order (lexicographically). The function should return a new dictionary with the sorted key-value pairs. The code should start with: ```python from typing import Dict...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def sort_dictionary_by_value_desc(dictionary: Dict[str, int]) -> Dict[str, int]: """ Sorts a dictionary by its values in descending order. If two or more keys have the same value, sort these keys by ...
code_exercise_27k
27,207
Write a Python function to remove all occurrences of a specified element from a given list. The function should return the updated list after removing all instances of the specified element. The code should start with: ```python from typing import List, Any def remove_element(lst: List[Any], element: Any) -> List[Any]...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def remove_element(lst: List[Any], element: Any) -> List[Any]: """ Remove all occurrences of a specified element from a list. Args: lst (List[Any]): The input list from which to remove ...
code_exercise_27k
27,209
Write a Python function to find the prime factors of a given number. The function should return a list of unique prime factors in ascending order. The code should start with: ```python from typing import List def prime_factors(n: int) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def prime_factors(n: int) -> List[int]: """ Returns a list of unique prime factors of a given number in ascending order. Args: n (int): The number to find the prime factors for. Returns...
code_exercise_27k
27,210
Write a Python function to calculate the Fibonacci series up to the nth term. The function should return a list containing the Fibonacci series up to the nth term. If `n` is less than or equal to 0, the function should return an empty list. The function should start with: ```python from typing import List def fibonacc...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def fibonacci_series(n: int) -> List[int]: """ Calculate the Fibonacci series up to the nth term. Args: n (int): The number of terms in the Fibonacci series. Returns: List[int]:...
code_exercise_27k
27,212
Write a Python function to perform binary search on a sorted list and return the index of the target element. If the target element is not found, return -1. The function should handle edge cases such as an empty list or a target that is not present in the list. 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, Any def binary_search(sorted_list: List[Any], target: Any) -> int: """ Perform binary search on a sorted list to find the position of a target element. Args: sorted_list (List[Any]): A sort...
code_exercise_27k
27,215
Write a Python function to implement Dijkstra's algorithm for finding the shortest path in a weighted graph. The graph is represented as a dictionary where each key is a node and the value is another dictionary representing the edges to neighboring nodes with their respective weights. The function should return two dic...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Tuple from heapq import heappop, heappush def dijkstra_shortest_path(graph: Dict[str, Dict[str, int]], start: str) -> Tuple[Dict[str, int], Dict[str, str]]: """ Implements Dijkstra's algorithm to find t...
code_exercise_27k
27,218
Write a Python function to find the largest and smallest number in a given list of integers without using the built-in `max()` and `min()` functions. The function should iterate through the list to determine the largest and smallest values. The code should start with: ```python from typing import List, Tuple def find...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def find_largest_smallest(numbers: List[int]) -> Tuple[int, int]: """ Find the largest and smallest number in a list without using built-in max() and min() functions. Args: numbers (L...
code_exercise_27k
27,220
Write a Python function to count the number of islands in a given grid (matrix). An island is defined as a group of adjacent land cells (represented by `1`). Two cells are considered adjacent if they are horizontally or vertically connected. The grid is represented as a 2D list of integers, where `1` represents land an...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_islands(grid: List[List[int]]) -> int: """ Counts the number of islands in a given grid matrix. Args: grid (List[List[int]]): A 2D grid matrix where 1 represents land and 0 represe...
code_exercise_27k
27,222
Write a Python function to find the length of the longest common subsequence (LCS) of two given strings. The function should return the length of the LCS, not the subsequence itself. The code should start with: ```python def longest_common_subsequence_length(str1: str, str2: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def longest_common_subsequence_length(str1: str, str2: str) -> int: """ Finds the length of the Longest Common Subsequence (LCS) of two given strings. Args: str1 (str): The first string. str2 (str): The ...
evol_instruct_66k
4
Write a Python function to find the highest number in a given array of integers without using the built-in `max` function. The function should iterate through the array and keep track of the highest number encountered. The code should start with: ```python from typing import List def find_highest_number(array: List[i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_highest_number(array: List[int]) -> int: """ Find the highest number in a given array of integers. Args: array (List[int]): The array of integers from which to find the highest numb...
evol_instruct_66k
5
Write a Python function to filter and sort a list of books based on specified criteria, including author, genre, and publication year. The function should also support pagination to limit the number of results returned per page. The code should start with: ```python from typing import List, Dict, Optional def filter_a...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Optional def filter_and_sort_books(books: List[Dict], author: Optional[str] = None, genre: Optional[str] = None, publication_year: Optional[int] = None, sort_by: Optional[str] =...
evol_instruct_66k
14
Write a Python function to calculate the sum of the squares of the elements in a given tuple. The function should also return a list of the squared values. The code should start with: ```python from typing import Tuple, List def sum_of_squares(input_tuple: Tuple[int]) -> Tuple[List[int], int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Tuple, List def sum_of_squares(input_tuple: Tuple[int]) -> Tuple[List[int], int]: """ Calculate the sum of the squares of the elements in a given tuple and return both the list of squared values and the sum. ...
evol_instruct_66k
19
Write a Python function to identify and replace all special characters and numbers in a given string with their corresponding ASCII values. The function should also handle uppercase and lowercase letters, preserving their original form in the output string. The code should start with: ```python def replace_special_and_...
Here is the Python code to solve the given problem in the markdown block: ```python import re def replace_special_and_numbers(string: str) -> str: """ Replaces all special characters and numbers in the given string with their corresponding ASCII values. Args: string (str): The input string to proc...
evol_instruct_66k
22
Write a Python function to calculate the final size of a list after invoking the `pop()` method a specified number of times. The function should take a list of integers and an integer representing the number of times to invoke the `pop()` method, and return the final size of the list. The code should start with: ```py...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def final_list_size(numbers: List[int], pop_count: int) -> int: """ Calculate the final size of a list after invoking the pop() method a specified number of times. Args: numbers (List[int]):...
evol_instruct_66k
31
Write a Python function to perform a zigzag level order traversal of a binary tree. The function should return a list of lists where each inner list represents a level of the tree, and the order of nodes in each level alternates between left-to-right and right-to-left. The code should start with: ```python from collec...
Here is the Python code to solve the given problem in the markdown block: ```python from collections import deque from typing import List, Optional class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def zigzag_level_order_tr...
evol_instruct_66k
33
Write a Python function to sanitize a dataset containing worldwide obesity rates. The function should convert every numerical string entry into its corresponding float representation and replace all non-numerical entries with the 'N/A' indicator. The code should start with: ```python from typing import List def saniti...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sanitize_dataset(dataset: List[List[str]]) -> List[List[str]]: """ Sanitize a dataset by converting numerical string entries to floats and replacing non-numerical entries with 'N/A'. Args: ...
evol_instruct_66k
54
Write a Python function to validate an email address based on the following constraints: 1. The local-part of the email address may only use alphanumerics and the characters: underscore, hyphen, period. 2. The domain part must be a top-level domain (like .com, .org, .net) with a maximum length of 6. 3. No consecutive p...
Here is the Python code to solve the given problem in the markdown block: ```python import re def validate_email(email: str) -> bool: """ Validates an email address based on the following constraints: 1. The local-part may only use alphanumerics and the characters: underscore, hyphen, period. 2. The do...
evol_instruct_66k
58
Write a Python function to create a new list where each element is the square of the corresponding element in a given list. The function should use list comprehension for this purpose. The code should start with: ```python from typing import List def square_elements(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 square_elements(input_list: List[int]) -> List[int]: """ Creates a new list where each element is the square of the corresponding element in the input list. Args: input_list (List[int]...
evol_instruct_66k
69
Write a Python function to arrange a sequential set of integers into triplets. The function should take a list of integers as input and return a list of triplets. If the number of integers is not a multiple of three, the remaining integers should be ignored. The code should start with: ```python from typing import Lis...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def arrange_into_triplets(nums: List[int]) -> List[List[int]]: """ Arrange a sequential set of integers into triplets. Args: nums (List[int]): A list of integers to be arranged into triplets...
evol_instruct_66k
72
Write a Python function to find the k-th smallest element in an unsorted list of integers. The function should efficiently handle large datasets and return the k-th smallest element without sorting the entire list. The code should start with: ```python from typing import List def find_kth_smallest(arr: List[int], k: ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import heapq def find_kth_smallest(arr: List[int], k: int) -> int: """ Find the k-th smallest element in an unsorted list of integers. Args: arr (List[int]): The unsorted list of integers. ...
evol_instruct_66k
83
Write a Python function to generate a table of addition of two numbers from a given list of tuples. Each tuple contains two integers, representing the numbers to be added. The function should return a list of tuples where each tuple contains the two original numbers and their sum. The code should start with: ```python...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def generate_addition_table(numbers: List[Tuple[int, int]]) -> List[Tuple[int, int, int]]: """ Generates a table of addition for a given list of tuples, where each tuple contains two integers. ...
evol_instruct_66k
86
Write a Python function to count the number of distinct alphanumeric characters in a given text string, ignoring case and spaces. The function should return the count of unique alphanumeric characters. The code should start with: ```python def count_distinct_alphanumeric(text_string: str) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def count_distinct_alphanumeric(text_string: str) -> int: """ Counts the number of distinct alphanumeric characters in a given text string, ignoring case and spaces. Args: text_string (str): The input text string fr...
evol_instruct_66k
97
Write a Python function to check if a given string ends with the word "Goodbye" using a regular expression. The function should return `True` if the string ends with "Goodbye", and `False` otherwise. The code should start with: ```python import re def ends_with_goodbye(input_string: str) -> bool: ```
Here is the Python code to solve the given problem in the markdown block: ```python import re def ends_with_goodbye(input_string: str) -> bool: """ Check if the given string ends with the word "Goodbye" using a regular expression. Args: input_string (str): The string to be checked. Returns: ...
evol_instruct_66k
116
Write a Python function to sort a list of dictionaries based on the values of the 'score' key in either ascending or descending order. The function should accept a list of dictionaries and a boolean flag indicating the order of sorting (True for descending, False for ascending). The code should start with: ```python fr...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Union def sort_by_score(lst: List[Dict[str, int]], descending: bool = False) -> List[Dict[str, int]]: """ Sorts a list of dictionaries based on the 'score' key in either ascending or descending or...
evol_instruct_66k
145
Write a Python function to calculate the mean of numerical elements within a given list. The function should use loops and summation operations before performing the division process. The code should start with: ```python from typing import List def calculate_mean(arr: 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(arr: List[int]) -> float: """ Calculate the mean of numerical elements within a given list. Args: arr (List[int]): The list of integers for which the mean is to be calcu...
evol_instruct_66k
158
Write a Python function to generate and print a Pascal's Triangle up to a specified number of rows. The function should return a list of lists where each inner list represents a row in the triangle. The code should start with: ```python from typing import List def generate_pascal_triangle(num_rows: int) -> List[List[i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def generate_pascal_triangle(num_rows: int) -> List[List[int]]: """ Generate a Pascal's Triangle up to the specified number of rows. Args: num_rows (int): The number of rows to generate in t...
evol_instruct_66k
165
Write a Python function to sort a list of positive integers by the length of their binary representation in increasing order. If two or more integers have the same binary length, sort them by their decimal values. The function should handle lists containing zero and positive integers. The code should start with: ```py...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_by_binary_len(arr: List[int]) -> List[int]: """ Sorts a list of positive integers by the length of their binary representation in increasing order. If two or more integers have the same bina...
evol_instruct_66k
169
Write a Python function to calculate the Levenshtein (edit) distance between two given strings. The Levenshtein distance is defined as the minimum number of single-character edits (insertions, deletions, substitutions) required to transform one string into another. The function should be efficient and handle strings of...
Here is the Python code to solve the given problem in the markdown block: ```python def levenshtein_distance(s1: str, s2: str) -> int: """ Calculate the Levenshtein (edit) distance between two strings. The Levenshtein distance is the minimum number of single-character edits (insertions, deletions, subs...
evol_instruct_66k
170
Write a Python function to perform Caesar cipher encryption on a given string with a specified shift value. The Caesar cipher shifts each letter in the string by a fixed number of positions down the alphabet. Non-alphabetic characters should remain unchanged. The function should be case-insensitive and should handle bo...
Here is the Python code to solve the given problem in the markdown block: ```python def caesar_cipher(text: str, shift: int) -> str: """ Encrypts the given text using the Caesar cipher with the specified shift value. Args: text (str): The input text to be encrypted. shift (int): The number ...
evol_instruct_66k
171
Write a Python function to calculate the element at a specific row and column in Pascal's Triangle. The function should handle invalid inputs gracefully by returning `None` for out-of-bound indices. Pascal's Triangle is a triangular array of binomial coefficients. The element at row `r` and column `c` (both 0-indexed) ...
Here is the Python code to solve the given problem in the markdown block: ```python import math def pascal_triangle_element(row: int, col: int) -> int: """ Calculate the element at the specified row and column in Pascal's Triangle. Args: row (int): The row index (0-indexed) in Pascal's Triangle. ...
evol_instruct_66k
185
Write a Python function to simulate a simple NoSQL-like database interaction for managing user records. The function should allow adding, retrieving, updating, and deleting user records, as well as retrieving all users. Each user record will be represented as a dictionary with keys 'id', 'name', and 'email'. The functi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict, Optional def add_user(users: List[Dict[str, str]], user: Dict[str, str]) -> None: """ Add a new user to the list of users. Args: users: A list of user dictionaries. user: A di...
evol_instruct_66k
206
Write a Python function to divide each pair of numbers in a given list of tuples and return the results in a new list. If a division by zero occurs, append the string "Error: Division by Zero" to the result list instead. The function should handle the division operation for each pair and manage potential exceptions. T...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def divide_pairs(pair_list: List[Tuple[int, int]]) -> List[float or str]: """ Divides each pair of numbers in a given list of tuples and returns the results in a new list. If a division by zer...
evol_instruct_66k
209
Write a Python function to select all employees whose last name is "Johnson" and who were hired in the last five years, ordered by their hire dates in descending order. The function should return a list of dictionaries, where each dictionary contains the employee's first name, last name, hire date, and salary after a 1...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import datetime, timedelta from typing import List, Dict def select_johnson_employees(employees: List[Dict[str, any]]) -> (List[Dict[str, any]], int): """ Selects all employees whose last name is "Johnson" and who...
evol_instruct_66k
221
Write a Python function to calculate the number of days in the current month, taking into account leap years. Additionally, create a function that calculates the number of days between two given dates (in the format "YYYY-MM-DD"). The code should start with: ```python from datetime import datetime, timedelta def days...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import datetime, timedelta def days_in_current_month() -> int: """ Calculate the number of days in the current month, considering leap years. Returns: int: The number of days in the current month. ...
evol_instruct_66k
223
Write a Python function to compare two phrases and determine if they contain the exact same distinct words, considering both case sensitivity and punctuation. The function should remove punctuation and split the phrases into sets of words, then compare these sets for equality. The code should start with: ```python impo...
Here is the Python code to solve the given problem in the markdown block: ```python import re def compare_word_sets(phrase1: str, phrase2: str) -> bool: """ Compare two phrases to determine if they contain the exact same distinct words, considering case sensitivity and punctuation. Args: phrase1 (...
evol_instruct_66k
247
Write a Python function that adds an item to a given sorted list in a way that the list remains sorted in ascending order. The list consists of numbers. You cannot use built-in Python functions to sort the list. The function should have optimal time and space complexity. The code should start with: ```python from typi...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def add_item_to_sorted_list(lst: List[int], item: int) -> List[int]: """ Adds an item to a sorted list in a way that the list remains sorted in ascending order. Args: lst (List[int]): The so...
evol_instruct_66k
294
Write a Python function to count the number of unique elements in a given list. The function should handle lists with duplicate elements and return the count of distinct elements. The code should start with: ```python from typing import List def count_unique_elements(lst: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_unique_elements(lst: List[int]) -> int: """ Counts the number of unique elements in a given list. Args: lst (List[int]): The list of integers from which to count unique elements. ...
evol_instruct_66k
297
Write a Python function to print a diamond numeric pattern in reverse order for a given integer `n`. The pattern should be centered and symmetric, with numbers decreasing from `n` to `1` and then increasing back to `n`. The function should start with: ```python def print_diamond_numeric_pattern(n: int) -> None: ```
Here is the Python code to solve the given problem in the markdown block: ```python def print_diamond_numeric_pattern(n: int) -> None: """ Prints a diamond numeric pattern in reverse order for a given integer n. Args: n (int): The integer to determine the size of the diamond pattern. Returns: ...
evol_instruct_66k
310
Write a Python function to reverse and print the elements of a given list. The function should take a list of integers as input and print each element in reverse order. The code should start with: ```python from typing import List def print_reverse_list(arr: List[int]) -> None: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def print_reverse_list(arr: List[int]) -> None: """ Prints the elements of the given list in reverse order. Args: arr (List[int]): The list of integers to be printed in reverse order. ...
evol_instruct_66k
313
Write a Python function to sort a list of numerical integer elements in descending order. The function should take a list of integers as input and return a new list with the elements sorted from the maximum to the minimum value. The original list should not be modified. 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 sort_descending(numbers: List[int]) -> List[int]: """ Sorts a list of numerical integer elements in descending order. Args: numbers (List[int]): The list of integers to be sorted. R...
evol_instruct_66k
331
Write a Python function to sort a dictionary by the number of vowels in each key. The keys are strings, and the function should return a new dictionary with the same key-value pairs but sorted by the number of vowels in ascending order. The code should start with: ```python from typing import Dict def sort_dictionary...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def count_vowels(word: str) -> int: """ Counts the number of vowels in a given string. Args: word (str): The string to count vowels in. Returns: int: The number of vowels in the...
evol_instruct_66k
340
Write a Python function to determine the square root of the smaller number between two given integers. The function should return the square root as a floating-point number. If both numbers are equal, the function should return the square root of either number. The code should start with: ```python import math def sq...
Here is the Python code to solve the given problem in the markdown block: ```python import math def square_root_of_smaller_number(num1: int, num2: int) -> float: """ Calculate the square root of the smaller number between two given integers. Args: num1 (int): The first integer. num2 (int):...
evol_instruct_66k
345
Write a Python function to convert a list of nested dictionaries into a list of tuples. If a dictionary within the list contains another dictionary as one of its values, each key-value pair from the nested dictionary should be represented as a separate tuple within the list. The function should handle multiple levels o...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple, Any def convert_nested_dicts_to_tuples(input_list: List[dict]) -> List[Tuple[str, Any]]: """ Converts a list of nested dictionaries into a list of tuples. Args: input_list (List[dict...
evol_instruct_66k
348
Write a Python function to generate a list of 15 random integers within the range of 50 to 100, inclusive. The function should ensure that each integer is within the specified range and should return the generated list. The code should start with: ```python from typing import List import random def generate_random_int...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def generate_random_integers() -> List[int]: """ Generates a list of 15 random integers within the range of 50 to 100, inclusive. Returns: List[int]: A list containing 15 rando...
evol_instruct_66k
353
Write a Python function to eliminate redundant entries from a given sequence while preserving the order of the first occurrence of each element. The sequence is a list of integers. The code should start with: ```python from typing import List def eliminate_redundant_entries(sequence: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def eliminate_redundant_entries(sequence: List[int]) -> List[int]: """ Eliminates redundant entries from the given sequence while preserving the order of the first occurrence of each element. Args: ...
evol_instruct_66k
367
Write a Python function to sort a given list of strings in alphabetical order. The list may contain strings representing fruits and animals. The function should return the sorted list. The code should start with: ```python from typing import List def sort_strings(list_of_strings: List[str]) -> List[str]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_strings(list_of_strings: List[str]) -> List[str]: """ Sorts a given list of strings in alphabetical order. Args: list_of_strings (List[str]): The list of strings to be sorted. ...
evol_instruct_66k
373
Write a Python function to create a lambda function that doubles the numerical value of the parameter passed to it. Additionally, write a function that applies this lambda function to each element of a list of integers and returns the resulting list. The code should start with: ```python from typing import List def c...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def create_doubling_lambda() -> callable: """ Create and return a lambda function that doubles the numerical value of the parameter passed to it. Returns: callable: A lambda function that do...
evol_instruct_66k
390
Write a Python function to find the top `n` most frequent words in a given sentence, ignoring case and punctuation. The function should return a list of tuples where each tuple contains a word and its frequency. The code should start with: ```python from typing import List, Tuple import string from collections import ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple import string from collections import Counter def top_n_frequent_words(sentence: str, n: int) -> List[Tuple[str, int]]: """ Find the top n most frequent words in a given sentence, ignoring case an...
evol_instruct_66k
425
Write a Python function to construct a new array where each element is the cube of the corresponding element in the original array. The function should take a list of integers as input and return a new list of integers. The code should start with: ```python from typing import List def cube_array(arr: List[int]) -> Li...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def cube_array(arr: List[int]) -> List[int]: """ Constructs a new array where each element is the cube of the corresponding element in the original array. Args: arr (List[int]): The original...
evol_instruct_66k
429
Write a Python function to extract and return the names of vehicles that are exclusively powered by electricity from a given list of all vehicles. The function should take two lists as input: one containing the names of all vehicles and another containing the names of vehicles that are exclusively electric. The functio...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def extract_electric_vehicles(all_vehicles: List[str], electric_vehicles: List[str]) -> List[str]: """ Extracts and returns the names of vehicles that are exclusively powered by electricity. Args: ...
evol_instruct_66k
441
Write a Python function to evaluate the equivalence of two provided dictionaries, considering both the keys and their corresponding values. The function should return `True` if the dictionaries are equivalent, and `False` otherwise. The code should start with: ```python from typing import Dict def are_dictionaries_equ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def are_dictionaries_equivalent(dict1: Dict[int, int], dict2: Dict[int, int]) -> bool: """ Evaluate the equivalence of two dictionaries, considering both the keys and their corresponding values. Arg...
evol_instruct_66k
445
Write a Python function to extract distinct elements from a given list of numbers and sort them in descending order. The function should handle lists with duplicate elements and return a list of unique elements sorted from the highest to the lowest value. The code should start with: ```python from typing import List ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_distinct_descending(numbers: List[int]) -> List[int]: """ Extracts distinct elements from a list of numbers and sorts them in descending order. Args: numbers (List[int]): A list of ...
evol_instruct_66k
447
Write a Python function to trim leading and trailing whitespace from a given text and also remove any extra whitespace between words. The function should accept texts of up to 10,000 characters. If the text exceeds this limit, the function should return an error message. The code should start with: ```python def trim_...
Here is the Python code to solve the given problem in the markdown block: ```python def trim_and_normalize_whitespace(text: str) -> str: """ Trims leading and trailing whitespace from the given text and removes any extra whitespace between words. If the text exceeds 10,000 characters, returns an error messa...
evol_instruct_66k
448
Write a Python function to find the frequency of a specific value in an array. The function should be efficient and handle both small and large arrays. The function should start with: ```python from typing import List def find_frequency(arr: List[int], value: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_frequency(arr: List[int], value: int) -> int: """ Find the frequency of a specific value in an array. Args: arr (List[int]): The array in which to find the frequency of the value. ...
evol_instruct_66k
452
Write a Python function that generates numbers from 0 to a given positive integer `n` (inclusive) and classifies each number as either 'even' or 'odd'. The function should return a list of tuples, where each tuple contains a number and its classification ('even' or 'odd'). The code should start with: ```python from ty...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def classify_numbers(n: int) -> List[Tuple[int, str]]: """ Classify numbers from 0 to n (inclusive) as either 'even' or 'odd'. Args: n (int): The upper limit of the range of numbers t...
evol_instruct_66k
460
Write a Python function to calculate the sum of all elements in a given two-dimensional array (list of lists). The function should handle any rectangular two-dimensional array, including those with different row lengths. The code should start with: ```python from typing import List def sum_2d_array(data: List[List[in...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sum_2d_array(data: List[List[int]]) -> int: """ Calculate the sum of all elements in a given two-dimensional array. Args: data (List[List[int]]): A two-dimensional array (list of lists) ...
evol_instruct_66k
478
Write a Python function to sort a dictionary by its values in a case-insensitive manner, ensuring the running time is no worse than O(n log n). The function should return a new dictionary with the sorted key-value pairs. The code should start with: ```python from typing import Dict def sort_dict_by_values_case_insens...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def sort_dict_by_values_case_insensitive(input_dict: Dict[str, str]) -> Dict[str, str]: """ Sorts a dictionary by its values in a case-insensitive manner and returns a new dictionary with sorted key-valu...
evol_instruct_66k
480
Write a Python function to find the length of the longest consecutive sequence of integers in a given list. The function should efficiently determine the longest sequence of consecutive numbers that can be formed from the elements of the list. The code should start with: ```python from typing import List def longest_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def longest_consecutive_sequence(nums: List[int]) -> int: """ Find the length of the longest consecutive elements sequence in a list of integers. Args: nums (List[int]): A list of integers f...
evol_instruct_66k
481
Write a Python function to scan through a multi-dimensional array and output every alternate element from each sub-array. The function should handle any size of multi-dimensional array and ensure that the output is correct and efficient. The code should start with: ```python from typing import List def print_alternat...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def print_alternate_elements(multi_array: List[List[int]]) -> None: """ Prints every alternate element from each sub-array in a multi-dimensional array. Args: multi_array (List[List[int]]): ...
evol_instruct_66k
497
Write a Python function to arrange a list in descending order without using the built-in `reverse()` or `sort()` methods. Instead, implement a custom sorting algorithm that uses the bubble sort technique to achieve the desired order. The code should start with: ```python from typing import List def sort_descending(ls...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_descending(lst: List[int]) -> List[int]: """ Sorts the given list in descending order using the bubble sort algorithm. Args: lst (List[int]): The list of integers to be sorted. ...
evol_instruct_66k
507
Write a Python function to generate an SQL query that updates each record in a table `main_table` by incorporating new values from a separate table `new_values_table`. The `main_table` has columns `id` and `value`, and the `new_values_table` also has columns `id` and `new_value`. The function should generate an SQL `UP...
Here is the Python code to solve the given problem in the markdown block: ```python def generate_update_query(main_table: str, new_values_table: str) -> str: """ Generates an SQL UPDATE query that updates each record in `main_table` by incorporating new values from `new_values_table`. Args: main_ta...
evol_instruct_66k
513
Write a Python function to calculate the product of all the non-negative, even elements in a given list. Handle empty lists and negative numbers. The function should return 1 if there are no non-negative, even elements in the list. The code should start with: ```python from typing import List def product_of_non_negat...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def product_of_non_negative_evens(num_list: List[int]) -> int: """ Calculate the product of all non-negative, even elements in the given list. Args: num_list (List[int]): The list of integer...
evol_instruct_66k
515
Write a Python function to determine if a target value exists in the values of a dictionary, using an efficient approach that avoids linear traversal of the dictionary. The function should leverage dictionary properties to improve performance. The code should start with: ```python def is_target_in_dict_values(my_dict:...
Here is the Python code to solve the given problem in the markdown block: ```python def is_target_in_dict_values(my_dict: dict, target: any) -> bool: """ Determines if a target value exists in the values of a given dictionary. Args: my_dict (dict): The dictionary to search in. target (any):...
evol_instruct_66k
517
Write a Python function to transform an array consisting of tuples, each containing a pair of numerical values, into an array of corresponding complex numbers. The function should take a list of tuples as input and return a list of complex numbers. The code should start with: ```python from typing import List, Tuple ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def transform_to_complex(tuple_array: List[Tuple[int, int]]) -> List[complex]: """ Transforms an array of tuples, each containing a pair of numerical values, into an array of corresponding complex...
evol_instruct_66k
520
Write a Python function to calculate the frequency of each unique alphabetic character in a given string, ignoring spaces. The function should return a dictionary where the keys are the characters and the values are their respective frequencies. The code should start with: ```python from typing import Dict def charac...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict from collections import Counter import re def character_frequency(input_string: str) -> Dict[str, int]: """ Calculate the frequency of each unique alphabetic character in the given string, ignoring space...
evol_instruct_66k
522
Write a Python function to standardize the casing of each individual word within a provided phrase by transforming them into lowercase letters. The function should handle phrases with multiple words separated by spaces and punctuation marks. The code should start with: ```python def standardize_casing(phrase: str) -> s...
Here is the Python code to solve the given problem in the markdown block: : ```python def standardize_casing(phrase: str) -> str: """ Standardizes the casing of each individual word within a provided phrase by transforming them into lowercase letters. Args: phrase (str): The input phrase to be stan...
evol_instruct_66k
523
Write a Python function to find the Greatest Common Divisor (GCD) of two non-negative integers using the Euclidean algorithm. The function should handle the case where one or both of the inputs are zero. 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 non-negative integers using the Euclidean algorithm. Args: a (int): The first non-negative integer. b (int): The second ...
evol_instruct_66k
551
Write a Python function to calculate the product of all odd integers in a given list. The function should ensure that the list only contains integers and has no more than 500 elements. The function should handle possible exceptions by raising appropriate errors. 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 product_of_odds(lst: List[int]) -> int: """ Calculate the product of all odd integers in a given list. Args: lst (List[int]): The list of integers to process. Returns: int: ...
evol_instruct_66k
553
Write a Python function to generate a new array where the sequence of elements is reversed compared to the original array provided. The function should handle arrays of any length and type of elements. The code should start with: ```python from typing import List, Any def reverse_array(input_array: List[Any]) -> List[...
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List, Any def reverse_array(input_array: List[Any]) -> List[Any]: """ Generates a new array where the sequence of elements is reversed compared to the original array provided. Args: input_array...
evol_instruct_66k
554
Write a Python function to find the capital city of a given European country from a predefined dictionary. If the country is not found in the dictionary, return "Country not found". The function should start with: ```python from typing import Dict, Optional def find_capital(country: str, capitals_dict: Dict[str, str])...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Optional def find_capital(country: str, capitals_dict: Dict[str, str]) -> Optional[str]: """ Find the capital city of a given European country from a predefined dictionary. Args: country (s...
evol_instruct_66k
575
Write a Python function to process a character sequence filled with numerical entities interspersed by comma demarcations. The function should identify and isolate the maximum numerical value within this collection. Subsequently, it should create a new character sequence consisting of the remaining numerical entities, ...
Here is the Python code to solve the given problem in the markdown block: ```python def process_sequence(seq: str) -> tuple: """ Processes a character sequence filled with numerical entities separated by commas. Identifies and isolates the maximum numerical value, then creates a new character sequence c...
evol_instruct_66k
582
Write a Python function to calculate the sum of all elements in a given list of integers. The function should iterate through each element in the list, add them together, and return the total sum. The code should start with: ```python from typing import List def sum_of_elements(lst: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def sum_of_elements(lst: List[int]) -> int: """ Calculate the sum of all elements in a given list of integers. Args: lst (List[int]): A list of integers whose elements are to be summed. ...
evol_instruct_66k
595
Write a Python function to eliminate redundant numerical values from a specified quantity of lists. The function should take a list of lists as input and return a list of lists where each sublist contains only unique values, maintaining the original order of 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 eliminate_redundant_values(list_of_lists: List[List[int]]) -> List[List[int]]: """ Eliminates redundant numerical values from each sublist in the input list of lists, while maintaining the origin...
evol_instruct_66k
597
Write a Python function to validate if a given string is in the standard American telephone number format `(XXX) XXX-XXXX`, where `X` is a digit. The function should return `True` if the string matches the format and `False` otherwise. The code should start with: ```python import re def is_valid_telephone_number(numb...
Here is the Python code to solve the given problem in the markdown block: ```python import re def is_valid_telephone_number(number: str) -> bool: """ Validates if the given string is in the standard American telephone number format '(XXX) XXX-XXXX'. Args: number (str): The string to be validated. ...
evol_instruct_66k
605
Write a Python function to print the numbers from 0 to n-1, where n is a positive integer provided as an argument. The function should handle any exceptions that might occur during the execution of the loop and print an error message if an exception is encountered. The code should start with: ```python def print_number...
Here is the Python code to solve the given problem in the markdown block: ```python def print_numbers(n: int) -> None: """ Prints the numbers from 0 to n-1. If an exception occurs during the execution, it prints an error message. Args: n (int): The upper limit (exclusive) for the range of numbe...
evol_instruct_66k
614
Write a Python function to generate an n x n Identity Matrix using the numpy library. The function should validate the input to ensure it is a positive integer and handle cases where the input is invalid by returning an empty array. The code should start with: ```python import numpy as np from typing import List def g...
Here is the Python code to solve the given problem in the markdown block: ```python import numpy as np from typing import List def generate_identity_matrix(n: int) -> List[List[float]]: """ Generate an n x n Identity Matrix using the numpy library. Args: n (int): The size of the Identity Matrix to...
evol_instruct_66k
617
Write a Python function to iterate over a list of integers, check if each integer is a prime number, and if it is, calculate and return the factorial of that prime number. If the integer is not a prime number, return `None` for that integer. The function should handle edge cases and errors appropriately. The code shoul...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Optional import math def prime_factorials(nums: List[int]) -> List[Optional[int]]: """ Iterates over a list of integers, checks if each integer is a prime number, and if it is, calculates and return...
evol_instruct_66k
625
Write a Python function to traverse two lists concurrently using a single `while` loop. The first list contains prime numbers, and the second list contains non-prime numbers. For each unique prime number in the prime list, compute and display its quadratic computation. For each unique non-prime number in the non-prime ...
Here is the Python code to solve the given problem in the markdown block: ```python import math from typing import List def traverse_lists(prime: List[int], non_prime: List[int]) -> None: """ Traverse two lists concurrently and perform specific operations on their elements. Args: prime (List[int])...
evol_instruct_66k
640
Write a Python function to compute the area of a rectangle given its length and width. The function should be designed to handle both positive and zero values for the dimensions. The code should start with: ```python def rectangle_area(length: float, width: float) -> float: ```
Here is the Python code to solve the given problem in the markdown block: ```python def rectangle_area(length: float, width: float) -> float: """ Computes the area of a rectangle given its length and width. Args: length (float): The length of the rectangle. width (float): The width of the r...
evol_instruct_66k
642
Write a Python function to compute the element-wise product of two lists and return a new list containing the products. The function should handle lists of different lengths by taking the minimum length of the two lists for the element-wise product calculation. The function should be optimized for both time and space c...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def element_wise_product(lst1: List[int], lst2: List[int]) -> List[int]: """ Computes the element-wise product of two lists and returns a new list containing the products. If the lists are of differe...
evol_instruct_66k
648
Write a Python function to generate a random string consisting of alphanumeric characters with a specified length. The function should ensure that the generated string contains exactly one digit and one uppercase letter. The code should start with: ```python import random import string def generate_random_string(lengt...
Here is the Python code to solve the given problem in the markdown block: : ```python import random import string from typing import List def generate_random_string(length: int) -> str: """ Generates a random string of the specified length, containing exactly one digit and one uppercase letter. Args: ...