source
stringclasses
6 values
id
int64
0
111k
instruction
stringlengths
167
4.39k
response
stringlengths
244
6.1k
code_exercise_27k
6,865
Write a Python function to find the sum of all prime numbers in a given list of integers. The function should be able to handle lists of varying sizes and should return the sum of all prime numbers found in the list. The function should start with: ```python from typing import List def sum_of_primes(numbers: List[int]...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_prime(n: int) -> bool: """Check if a number is prime. Parameters: n (int): The number to check. Returns: bool: True if the number is prime, False otherwise. """ if n < 2: ...
code_exercise_27k
6,867
Write a Python function to remove elements from a given list that are repeated at least 'N' times. The function should return a new list with the specified elements removed. The code should start with: ```python from typing import List def remove_repeated_elements(lst: List[int], N: int) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def remove_repeated_elements(lst: List[int], N: int) -> List[int]: """ Removes elements from a list that are repeated at least 'N' times. Args: lst (List[int]): The input list of integers....
code_exercise_27k
6,871
Write a Python function to remove elements from a given list that occur only once. The function should return a new list containing only the elements that have more than one occurrence in the original list. The code should start with: ```python from typing import List def remove_elements_with_single_occurrence(lst: Li...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_elements_with_single_occurrence(lst: List[int]) -> List[int]: """ Removes elements from the list that occur only once and returns a new list with elements that have more than one occurrence. ...
code_exercise_27k
6,872
Write a Python function to calculate the difference between two given dates in months, considering the day of the month. The function should handle cases where the day of the month in the second date is less than the day of the month in the first date, which should reduce the month difference by one. The function shoul...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import datetime def get_months_difference_with_day(date1: str, date2: str) -> int: """ Calculate the difference between two dates in months, considering the day of the month. Parameters: date1 (str): ...
code_exercise_27k
6,874
Write a Python function to update the value associated with the key "city" in a nested dictionary inside the "address" key of a main dictionary to be 'Los Angeles'. The function should handle cases where the "address" key or the "city" key might be missing. If the "address" key is missing, it should add a new nested di...
Here is the Python code to solve the given problem in the markdown block: ```python def update_city(address: dict) -> dict: """ Update the value associated with the key 'city' in the nested dictionary inside 'address' to be 'Los Angeles'. If the 'address' key is missing, it will add a new nested dictionary ...
code_exercise_27k
6,877
Write a Python function to calculate the difference in years between two given dates, considering the exact day and month to ensure the accuracy of the year difference. The function should handle cases where the end date is before the start date by returning a negative difference. The code should start with: ```python...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import date def get_year_difference(start_date: date, end_date: date) -> int: """ Calculates the difference in years between two dates, considering the exact day and month. Args: start_date (date): Th...
code_exercise_27k
6,883
Write a Python function to update the grade of a specific student in a given dictionary of student records. The function should take a dictionary of student records, the name of the student, the position of the grade to update (starting from 1), and the new grade. The function should return the updated dictionary. If t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def update_grade(records: Dict[str, List[int]], student_name: str, grade_number: int, new_grade: int) -> Dict[str, List[int]]: """ Update the grade of a specific student in the records dictionary. ...
code_exercise_27k
6,884
Write a Python function to shift all the elements of a list to the right by a specified number of positions. The function should handle both positive and negative shift values, where a positive value indicates a right shift and a negative value indicates a left shift. The function should also handle edge cases such as ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def shift_elements(lst: List[int], shift: int) -> List[int]: """ Shifts all the elements of a list to the right by a specified number of positions. A positive shift value indicates a right shift, and...
code_exercise_27k
6,887
Write a Python function to calculate the difference in hours between two given datetime objects, considering both positive and negative differences. The function should handle datetime objects in any order and return the absolute difference in hours. The code should start with: ```python from datetime import datetime ...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import datetime def get_absolute_time_difference_in_hours(datetime1: datetime, datetime2: datetime) -> int: """ Calculate the absolute difference in hours between two given datetime objects. Args: dat...
code_exercise_27k
6,889
Write a Python function to update the grades of a student in a given dictionary. If the student already exists in the dictionary, append the new grade to their existing list of grades. If the student does not exist, create a new entry for the student with the given grade as their first grade. The function should return...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Union def update_student_grades(records: Dict[str, List[int]], student: str, grade: int) -> Dict[str, List[int]]: """ Updates the grades of a student in the given records dictionary. If the s...
code_exercise_27k
6,890
Write a Python function to filter a list of strings based on their length, returning only those strings whose length is less than a given maximum length. The function should handle edge cases such as an empty list or a maximum length of zero. The code should start with: ```python from typing import List def filter_st...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def filter_strings_by_length(lst: List[str], max_length: int) -> List[str]: """ Filters a list of strings to include only those whose length is less than a given maximum length. Args: lst (L...
code_exercise_27k
6,902
Write a Python function to update the sales data for a given product and month in a nested dictionary. The function should take a dictionary containing sales data, a product name, a month, and a new sales quantity as inputs. It should update the sales quantity for the specified product and month and return the updated ...
Here is the Python code to solve the given problem in the markdown block: ```python def update_sales_data(sales_data: dict, product: str, month: str, quantity: int) -> dict: """ Update the sales data for a given product and month in the sales_per_month dictionary. Args: sales_data (dict): The dicti...
code_exercise_27k
6,905
Write a Python function to remove elements from a list that have a length less than a given value. The function should return the modified list containing only the elements whose lengths are greater than or equal to the specified length. The code should start with: ```python from typing import List def remove_short_el...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_short_elements(lst: List[str], min_length: int) -> List[str]: """ Remove elements from the list whose length is less than the specified minimum length. Args: lst (List[str]): The ...
code_exercise_27k
6,906
Write a Python function to remove a specified key-value pair from a dictionary. If the key does not exist in the dictionary, the function should return the original dictionary without any changes. The function should not raise any exceptions. The code should start with: ```python def remove_key_value_pair(dictionary: ...
Here is the Python code to solve the given problem in the markdown block: ```python def remove_key_value_pair(dictionary: dict, key) -> dict: """ Remove a specified key-value pair from a dictionary if the key exists. If the key does not exist, return the original dictionary without any changes. Args: ...
code_exercise_27k
6,923
Write a Python function to add a new expense to a given expenses dictionary. The expenses dictionary is structured such that it contains months as keys, and each month has a dictionary of categories and their corresponding expenses as values. The function should handle the addition of a new expense for a given month an...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def add_expense(expenses: Dict[str, Dict[str, float]], month: str, category: str, amount: float) -> Dict[str, Dict[str, float]]: """ Add a new expense to the expenses dictionary. Args: expen...
code_exercise_27k
6,930
Write a Python function to remove elements from a given list that lie within a specified range. The function should return the modified list with the elements removed. The code should start with: ```python from typing import List def remove_elements_in_range(lst: List[int], lower: int, upper: int) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def remove_elements_in_range(lst: List[int], lower: int, upper: int) -> List[int]: """ Remove elements from a list that lie within a specified range [lower, upper]. Args: lst (List[int]): Th...
code_exercise_27k
6,933
Write a Python function to update the grade of a student in a dictionary. The dictionary contains student names as keys, and each student's grades are stored in a nested dictionary with subjects as keys and grades as values. The function should update the grade of a specified student in a specified subject with a new g...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def update_grade(students: Dict[str, Dict[str, int]], student_name: str, subject: str, new_grade: int) -> Dict[str, Dict[str, int]]: """ Update the grade of a specified student in a specified subject in ...
code_exercise_27k
6,935
Write a Python function to calculate the total number of seconds in a given year, considering whether the year is a leap year or not. The function should return the total number of seconds as an integer. The code should start with: ```python def calculate_seconds_in_year(year: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def calculate_seconds_in_year(year: int) -> int: """ Calculate the total number of seconds in a given year. Args: year (int): The year for which to calculate the total number of seconds. Returns: int: T...
code_exercise_27k
6,939
Write a Python function to add a new course grade for a given student in a dictionary that stores student information. If the student does not exist in the dictionary, the function should raise a `KeyError`. The function should return the updated dictionary. The code should start with: ```python from typing import Dic...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Any def add_course_grade(students: Dict[str, Dict[str, Any]], student_name: str, course: str, grade: int) -> Dict[str, Dict[str, Any]]: """ Add a new course grade for a given student in the students dic...
code_exercise_27k
6,941
Write a Python function to determine the total number of days in a given month of a year, considering leap years. The function should handle invalid month values by raising a `ValueError`. The code should start with: ```python def get_total_days(year: int, month: int) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python def get_total_days(year: int, month: int) -> int: """ Calculate the total number of days in a given month of a year. Parameters: year (int): The year for which the total days have to be calculated. month (int): The ...
code_exercise_27k
6,942
Write a Python function to create a dictionary representing a person's information, including their name, age, and address. The address should be a nested dictionary containing the street, city, and country. The function should return this dictionary. The code should start with: ```python from typing import Dict def ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def create_person_info() -> Dict[str, any]: """ Creates a dictionary representing a person's information, including their name, age, and address. Returns: Dict[str, any]: A dictionary contai...
code_exercise_27k
6,948
Write a Python function to check if two given dates are equal, considering that the dates may be provided in different formats. The function should be able to handle various date formats such as 'YYYY-MM-DD', 'MM/DD/YYYY', 'DD-MM-YYYY', and 'YYYY/MM/DD'. The function should return `True` if the dates represent the same...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import datetime def are_dates_equal(date1: str, date2: str) -> bool: """ Check if two given dates are equal, regardless of their format. Parameters: date1 (str): The first date string. date2 (str): Th...
code_exercise_27k
6,949
Write a Python function to update the country of the address in a given dictionary representing a person's information. The function should handle the case where the 'address' or 'country' keys are missing by raising a `KeyError`. The function should start with: ```python def update_address_country(person_dict: dict, n...
Here is the Python code to solve the given problem in the markdown block: ```python def update_address_country(person_dict: dict, new_country: str) -> dict: """ Update the country of the address in the given person dictionary. Args: person_dict (dict): A dictionary representing a person's informati...
code_exercise_27k
6,950
Write a Python function to update an element in a list at a specified index. The function should handle both positive and negative indices and raise an `IndexError` if the index is out of range. The function should return the updated list. The code should start with: ```python from typing import List, Any def update_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def update_element(lst: List[Any], index: int, new_value: Any) -> List[Any]: """ Update an element in a list at the specified index. Args: lst (List[Any]): The list to be updated. ...
code_exercise_27k
6,953
Write a Python function to remove all occurrences of a specified element from a given list. The function should return the updated list without modifying the original list. 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 given list. This function takes a list (lst) and an element (element) as ...
code_exercise_27k
6,957
Write a Python function to retrieve and return the name and salary of a specified employee from a given dictionary. The dictionary contains employee information, where each key is an employee identifier (e.g., "employee1", "employee2"), and the corresponding value is a nested dictionary containing the employee's name a...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Tuple def get_employee_info(employees: Dict[str, Dict[str, any]], employee_id: str) -> Tuple[str, int]: """ Retrieves and returns the name and salary of a specified employee from a given dictionary. ...
code_exercise_27k
6,961
Write a Python function to count the occurrences of an element in a given list without using the built-in `count` method. The function should iterate through the list and maintain a count of how many times the specified element appears. The code should start with: ```python from typing import List def count_occurrenc...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def count_occurrences(lst: List[int], element: int) -> int: """ Count the occurrences of an element in a list without using the built-in count method. Args: lst (List[int]): The list to sear...
code_exercise_27k
6,963
Write a Python function to update the salary of an employee in a given dictionary of employees. The function should handle the following: 1. Update the salary of the specified employee. 2. Raise a `KeyError` if the employee name is not found in the dictionary. 3. Raise a `TypeError` if the new salary is not a numeric v...
Here is the Python code to solve the given problem in the markdown block: ```python def update_employee_salary(employees: dict, employee_name: str, new_salary: float) -> dict: """ Update the salary of an employee in the employees dictionary. Parameters: employees (dict): A dictionary containing employe...
code_exercise_27k
6,966
Write a Python function to remove a specific key-value pair from a given dictionary. If the key does not exist in the dictionary, the function should return the original dictionary without any changes. The function should start with: ```python def remove_key_value_pair(dictionary: dict, key: str) -> dict: ```
Here is the Python code to solve the given problem in the markdown block: ```python def remove_key_value_pair(dictionary: dict, key: str) -> dict: """ Removes a specific key-value pair from a given dictionary. Args: dictionary (dict): The dictionary from which the key-value pair should be removed. ...
code_exercise_27k
6,968
Write a Python function to create a dictionary called "courses" with the specified key-value pairs. The keys are course names, and the values are lists of students enrolled in those courses. The function should return the dictionary. The code should start with: ```python from typing import Dict, List def create_cours...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def create_courses_dictionary() -> Dict[str, List[str]]: """ Create a dictionary called "courses" with the specified key-value pairs. The keys are course names, and the values are lists of stu...
code_exercise_27k
6,973
Write a Python function to find the sum of all elements in a list, but with a twist: the function should also handle nested lists, where each nested list can contain other nested lists. The function should recursively sum all elements, regardless of the nesting level. 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 Union, List def sum_of_nested_list_elements(lst: Union[List[Union[int, float, List]], int, float]) -> Union[int, float]: """ Recursively calculates the sum of all elements in a list, including elements in nes...
code_exercise_27k
6,976
Write a Python function to add a new student to a specific course in a dictionary that maps course names to lists of enrolled students. If the course does not exist in the dictionary, create a new entry for the course and add the student to it. The function should return the updated dictionary. The code should start w...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def add_student_to_course(courses: Dict[str, List[str]], course_name: str, student_name: str) -> Dict[str, List[str]]: """ Adds a new student to a specific course in the courses dictionary. If ...
code_exercise_27k
6,977
Write a Python function to calculate the product of all elements in a given list of integers. The function should handle the case where the list is empty by raising a `ValueError`. The code should start with: ```python from typing import List def product_of_list_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 product_of_list_elements(lst: List[int]) -> int: """ Calculate the product of all elements in a given list of integers. Args: lst (List[int]): A list of integers. Returns: i...
code_exercise_27k
6,980
Write a Python function to find the largest element in a given list of integers. If the list is empty, raise a `ValueError` with the message "List is empty." The function should start with: ```python from typing import List def find_largest_element(arr: 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_element(arr: List[int]) -> int: """ Returns the largest element in a given list of integers. Args: arr (List[int]): The input list of integers. Returns: int: Th...
code_exercise_27k
6,982
Write a Python function to determine if a given date is a weekend day. The function should take the year, month, and day as inputs and return `True` if the date is a weekend day (Saturday or Sunday), and `False` otherwise. The code should start with: ```python import datetime def is_weekend(year: int, month: int, day:...
Here is the Python code to solve the given problem in the markdown block: ```python import datetime def is_weekend(year: int, month: int, day: int) -> bool: """ Determine if a given date is a weekend day. Args: year (int): The year of the date. month (int): The month of the date. d...
code_exercise_27k
6,990
Write a Python function to update a specific grade in a given dictionary of grades. The function should take a dictionary of grades, a subject (as a string), and a new grade (as an integer). If the subject exists in the dictionary, the function should update the grade for that subject. If the subject does not exist, th...
Here is the Python code to solve the given problem in the markdown block: ```python def update_grade(grades: dict, subject: str, grade: int) -> dict: """ Update a specific grade in the given grades dictionary. Args: grades (dict): A dictionary of grades where keys are subjects and values are grades...
code_exercise_27k
6,991
Write a Python function to determine if a given date is a valid date. The function should take three integers as input: the year, month, and day. The function should return `True` if the date is valid and `False` otherwise. A valid date must satisfy the following conditions: - The year must be a positive integer. - The...
Here is the Python code to solve the given problem in the markdown block: ```python def is_valid_date(year: int, month: int, day: int) -> bool: """ Determine if a given date is a valid date. Args: year (int): The year of the date. month (int): The month of the date. day (int): The d...
code_exercise_27k
6,992
Write a Python function to insert an element at a specific position in a list. The function should handle cases where the position is out of bounds by inserting the element at the beginning or the end of the list, respectively. The code should start with: ```python from typing import List, Any def insert_element_at_po...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def insert_element_at_position(lst: List[Any], element: Any, position: int) -> List[Any]: """ Insert an element at a specific position in a list. If the position is out of bounds, the element is...
code_exercise_27k
6,994
Write a Python function to calculate the number of days between two given dates. The function should take two `datetime.date` objects as input and return the number of days between them. If the future date is earlier than the current date, the function should raise a `ValueError`. The code should start with: ```python...
Here is the Python code to solve the given problem in the markdown block: ```python import datetime def get_days_between_dates(current_date: datetime.date, future_date: datetime.date) -> int: """ Calculate the number of days between current_date and future_date. Args: current_date (datetime.date):...
code_exercise_27k
6,996
Write a Python function to remove all occurrences of a specified element from a given list. The function should return a new list with all instances of the specified element removed, while preserving the order of the remaining elements. The code should start with: ```python from typing import List, Any def remove_all_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def remove_all_occurrences(lst: List[Any], element: Any) -> List[Any]: """ Remove all occurrences of a specified element from a given list. Args: lst (List[Any]): The list from which to...
code_exercise_27k
6,997
Create a Python function that takes a dictionary of country populations (in millions) and a list of country names, and returns a new dictionary containing only the populations of the specified countries. If a country name in the list does not exist in the original dictionary, it should be ignored. The code should star...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def filter_population_by_countries(population: Dict[str, float], countries: List[str]) -> Dict[str, float]: """ Filters the population dictionary to include only the populations of the specified co...
code_exercise_27k
7,000
Write a Python function to merge two lists into a new list while maintaining the order of elements from both lists. The function should handle lists of any type, including nested lists and mixed types. The code should start with: ```python from typing import List, Any def merge_lists(list1: List[Any], list2: List[Any]...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def merge_lists(list1: List[Any], list2: List[Any]) -> List[Any]: """ Merge two lists into a new list while maintaining the order of elements from both lists. Args: list1 (List[Any]): T...
code_exercise_27k
7,004
Write a Python function to calculate the number of business days (excluding weekends) between two given dates. The function should accept two date strings in 'YYYY-MM-DD' format and return the number of business days between these dates. The function should handle date validation to ensure that the start date is not gr...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import date, timedelta def get_business_days(start_date: str, end_date: str) -> int: """ Calculates the number of business days (weekdays) between two dates, excluding weekends. Args: start_date (str)...
code_exercise_27k
7,005
Write a Python function to update the population of a country in a given dictionary. If the country is not found in the dictionary, the function should raise a `KeyError`. The function should return the updated dictionary. The code should start with: ```python def update_population(population_dict: dict, country: str,...
Here is the Python code to solve the given problem in the markdown block: ```python def update_population(population_dict: dict, country: str, population: int) -> dict: """ Update the population of a country in the population dictionary. Args: population_dict (dict): A dictionary containing country...
code_exercise_27k
7,008
Write a Python function to remove all occurrences of a specified key from a given dictionary. If the key does not exist in the dictionary, the function should return the dictionary unchanged. The function should handle nested dictionaries, meaning if the dictionary contains other dictionaries as values, the function sh...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Any, Dict def remove_key_from_dict(dictionary: Dict[Any, Any], key: Any) -> Dict[Any, Any]: """ Removes all occurrences of the specified key from the given dictionary, including nested dictionaries. Args...
code_exercise_27k
7,009
Write a Python function to calculate the number of business days between two given dates, excluding specified holidays. The function should handle the following: 1. Accept two `datetime.date` objects representing the start and end dates. 2. Optionally accept a list of `datetime.date` objects representing holidays. 3. R...
Here is the Python code to solve the given problem in the markdown block: ```python import datetime from typing import List, Optional def get_business_days(start_date: datetime.date, end_date: datetime.date, holidays: Optional[List[datetime.date]] = None) -> int: """ Calculate the number of business days betwe...
code_exercise_27k
7,012
Write a Python function to calculate the number of business days between two given dates, inclusive. The function should handle both string and `datetime.date` object inputs for the dates. The function should return the number of business days (Monday to Friday) between the start date and the end date, inclusive. The ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Union import datetime def get_business_days(start_date: Union[str, datetime.date], end_date: Union[str, datetime.date]) -> int: """ Calculate the number of business days between two given dates, inclusive. ...
code_exercise_27k
7,017
Write a Python function to sort a list of lists based on the second element of each sublist. If two sublists have the same second element, sort them based on their first element. The function should handle lists of varying lengths and ensure stability in sorting. The code should start with: ```python from typing impor...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def sort_list_of_lists(lst: List[List[int]]) -> List[List[int]]: """ Sorts a list of lists based on the second element of each sublist. If two sublists have the same second element, sort them based o...
code_exercise_27k
7,018
Write a Python function to calculate the total price of a list of products based on their identifiers. The function should take a dictionary of products and a list of product identifiers as input and return the total price of the specified products. The code should start with: ```python from typing import Dict, List ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def calculate_total_price(products: Dict[str, Dict[str, any]], product_ids: List[str]) -> int: """ Calculate the total price of a list of products based on their identifiers. Args: pro...
code_exercise_27k
7,023
Write a Python function to check if a given list of integers is a palindrome. A list is considered a palindrome if it reads the same backward as forward. The function should return `True` if the list is a palindrome and `False` otherwise. The code should start with: ```python from typing import List def is_palindrome_...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def is_palindrome_list(lst: List[int]) -> bool: """ Check if a list of integers is a palindrome. A list is considered a palindrome if it reads the same backward as forward. Args: lst (L...
code_exercise_27k
7,030
Write a Python function to add a new product to a given dictionary of products. Each product is represented by a dictionary with keys 'name' and 'price'. The function should take the existing products dictionary, a product ID, a product name, and a product price as arguments, and return the updated products dictionary....
Here is the Python code to solve the given problem in the markdown block: ```python def add_product(products: dict, product_id: str, name: str, price: float) -> dict: """ Add a new product to the products dictionary. Args: products (dict): The dictionary containing the products. product_id ...
code_exercise_27k
7,032
Write a Python function to get the month name from a given date string in the format "YYYY-MM-DD". The function should parse the date string, extract the month, and return the full name of the month. The code should start with: ```python from datetime import datetime def get_month_name_from_date_string(date_string: s...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import datetime def get_month_name_from_date_string(date_string: str) -> str: """ Get the month name from a given date string in the format "YYYY-MM-DD". Args: date_string (str): A date string in the ...
code_exercise_27k
7,039
Write a Python function to update the quantity of a specific product in a store dictionary. If the product does not exist in the store, add it with the specified quantity. The function should return the updated store dictionary. The code should start with: ```python from typing import Dict, Union def update_quantity(...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Union def update_quantity(store: Dict[str, int], product: str, quantity: int) -> Dict[str, int]: """ Update the quantity of a specific product in the store dictionary. If the product does not exist ...
code_exercise_27k
7,040
Write a Python function to find the index of the first occurrence of a sublist within a larger list. If the sublist is not found, the function should return -1. The function should be efficient and handle edge cases such as empty lists and sublists longer than the larger list. The code should start with: ```python fro...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_sublist_index(larger_list: List[int], sublist: List[int]) -> int: """ Find the index of the first occurrence of a sublist within a larger list. Args: larger_list (List[int]): The la...
code_exercise_27k
7,044
Write a Python function to generate all possible combinations of a given list of elements. Each combination should be represented as a tuple, and the function should return a list of all such tuples. The function should handle lists of varying lengths and ensure that all combinations, including the empty combination, a...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple from itertools import combinations def generate_all_combinations(elements: List[int]) -> List[Tuple[int]]: """ Generate all possible combinations of a given list of elements. Args: el...
code_exercise_27k
7,049
Write a Python function to find the maximum product of two distinct elements in a given list of integers. The function should return the maximum product. If the list contains fewer than two elements, the function should raise a `ValueError`. The code should start with: ```python from typing import List def find_max_p...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_max_product(nums: List[int]) -> int: """ Find the maximum product of two distinct elements in a list. Args: nums (List[int]): List of integers. Returns: int: Maximum pr...
code_exercise_27k
7,054
Write a Python function to add a new member to a specific team in a dictionary of teams. Each team is represented as a key in the dictionary, and its value is a list of members. If the team does not exist in the dictionary, create a new team with the new member. The function should return the updated dictionary. The c...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List, Union def add_member_to_team(teams: Dict[str, List[str]], team_name: str, new_member: str) -> Dict[str, List[str]]: """ Adds a new member to a specific team in the teams dictionary. Args: ...
code_exercise_27k
7,069
Write a Python function to update the name of a student in a dictionary based on the student's index. The dictionary contains student information where keys are strings (e.g., "student1", "student2") and values are the names of the students. The function should take the dictionary, the index of the student to be update...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def update_student_name(students: Dict[str, str], student_index: int, new_name: str) -> Dict[str, str]: """ Update the name of a student in the students dictionary based on the student's index. Args...
code_exercise_27k
7,072
Write a Python function to merge two dictionaries, ensuring that no duplicate keys exist in the resulting dictionary. If a key exists in both dictionaries, raise a `KeyError`. The function should start with: ```python def merge_dictionaries(dict1: dict, dict2: dict) -> dict: ```
Here is the Python code to solve the given problem in the markdown block: ```python def merge_dictionaries(dict1: dict, dict2: dict) -> dict: """ Merge two dictionaries, ensuring that no duplicate keys exist. Args: dict1 (dict): The first dictionary to merge. dict2 (dict): The second dictio...
code_exercise_27k
7,074
Write a Python function to shuffle a list randomly without modifying the original list. The function should return a new list with the elements shuffled. The code should start with: ```python from typing import List import random def shuffle_list(lst: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def shuffle_list(lst: List[int]) -> List[int]: """ Shuffle a list randomly without modifying the original list. Args: lst (List[int]): The list to be shuffled. Returns: ...
code_exercise_27k
7,076
Write a Python function to split a given datetime object into separate components (year, month, day, hour, minute, second) and return them as a dictionary. The function should handle datetime objects from the `datetime` module. The code should start with: ```python from datetime import datetime def split_datetime_to_d...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import datetime def split_datetime_to_dict(dt: datetime) -> dict: """ Split a given datetime object into separate components and return them as a dictionary. Args: dt (datetime): The datetime object t...
code_exercise_27k
7,077
Write a Python function to update the quantity of a product in a given dictionary of products. The function should take the product ID, the new quantity, and the dictionary of products as inputs, and return the updated dictionary. If the product ID does not exist in the dictionary, the function should raise a `KeyError...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def update_product_quantity(product_id: str, new_quantity: int, products: Dict[str, Dict[str, any]]) -> Dict[str, Dict[str, any]]: """ Update the quantity of a product in the given dictionary of products...
code_exercise_27k
7,080
Write a Python function to find the largest prime number in a given list of integers. If the list contains no prime numbers, the function should return `None`. The function should be efficient and handle edge cases such as an empty list or a list with non-prime numbers only. 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, Optional def is_prime(n: int) -> bool: """ Check if a number is prime. Parameters: n (int): The number to check. Returns: bool: True if the number is prime, False otherwise. """ ...
code_exercise_27k
7,082
Write a Python function to concatenate two lists together and return the result. The function should handle lists of any type, including nested lists. The function should also ensure that both inputs are lists and raise a `TypeError` if either input is not a list. 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, Any def concatenate_lists(list1: List[Any], list2: List[Any]) -> List[Any]: """ Concatenates two lists together and returns the result. Args: list1 (List[Any]): The first list to be concate...
code_exercise_27k
7,084
Write a Python function to concatenate three lists together and return the resulting list. The function should handle lists of any length, including empty lists. The code should start with: ```python from typing import List def concatenate_lists(list1: List[int], list2: List[int], list3: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def concatenate_lists(list1: List[int], list2: List[int], list3: List[int]) -> List[int]: """ Concatenates three lists together and returns the resulting list. Args: list1 (List[int]): The f...
code_exercise_27k
7,087
Write a Python function to merge two lists by interleaving their elements. If one list is longer than the other, the remaining elements of the longer list should be appended at the end of the merged list. The function should start with: ```python from typing import List def interleave_lists(list1: List[int], list2: Li...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def interleave_lists(list1: List[int], list2: List[int]) -> List[int]: """ Merges two lists by interleaving their elements. If one list is longer than the other, the remaining elements of the longer ...
code_exercise_27k
7,089
Write a Python function to concatenate a list and a tuple into a new list. The function should take two parameters: a list and a tuple. The function should return a new list that contains all elements from the input list followed by all elements from the input tuple. The code should start with: ```python from typing i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Tuple def concatenate_list_tuple(input_list: List, input_tuple: Tuple) -> List: """ Concatenates a list and a tuple into a new list. Args: input_list (List): The list to be concatenated. ...
code_exercise_27k
7,092
Write a Python function to calculate the total expenses for a given month and category from a dictionary of monthly expenses. The dictionary contains nested dictionaries where the outer keys are months and the inner keys are categories of expenses. The function should return the total expense for the specified month an...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def calculate_total_expense(expenses: Dict[str, Dict[str, int]], month: str, category: str) -> int: """ Calculate the total expense for a given month and category from a dictionary of monthly expenses. ...
code_exercise_27k
7,095
Write a Python function to find the missing number in a given list of consecutive integers from 1 to n, where one number is missing. The function should return the missing number. The code should start with: ```python from typing import List def find_missing_number(lst: List[int]) -> int: ```
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def find_missing_number(lst: List[int]) -> int: """ Finds the missing number in a given list of consecutive integers from 1 to n, where one number is missing. Args: lst (List[int]): A li...
code_exercise_27k
7,096
Write a Python function to concatenate a list and an integer, ensuring that the integer is converted to a string before being appended to the list. The function should handle cases where the list is empty and where the integer is zero or negative. The code should start with: ```python from typing import List def conca...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def concatenate_list_and_integer(lst: List[int], num: int) -> List[str]: """ Concatenates a list of integers and an integer, converting the integer to a string before appending. This function takes ...
code_exercise_27k
7,098
Write a Python function to concatenate a list and a float, ensuring that the float is appended to the end of the list. The function should handle input validation to ensure that the provided arguments are of the correct types. If the input types are incorrect, the function should raise a `TypeError`. The code should s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def concatenate_list_and_float(lst: List[int], flt: float) -> List[int]: """ Concatenates a list and a float, appending the float to the end of the list. Args: lst (List[int]): The list to b...
code_exercise_27k
7,101
Write a Python function to calculate the number of weeks between two given dates. The function should accept two date strings in the format 'YYYY-MM-DD' and return the number of weeks between these dates as an integer. The function should handle cases where the start date is later than the end date by returning a negat...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import datetime def weeks_between_dates(start_date: str, end_date: str) -> int: """ Calculate the number of weeks between two given dates. Args: start_date (str): The start date in the format 'YYYY-MM...
code_exercise_27k
7,102
Write a Python function to concatenate the elements of two lists alternatively. The function should take two lists as input and return a new list containing the elements of the first list followed by the elements of the second list, alternating between the two lists. If the lists have different lengths, the function sh...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def concatenate_alternatively(list1: List, list2: List) -> List: """ Concatenates the elements of two lists alternatively. Args: list1 (List): The first list. list2 (List): The secon...
code_exercise_27k
7,105
Write a Python function to concatenate two lists in a zigzag pattern. The function should take two lists as input and return a new list where elements from the first list are placed at even indices and elements from the second list are placed at odd indices. If the lengths of the two lists are not equal, the function s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def zigzag_concatenate(list1: List[int], list2: List[int]) -> List[int]: """ Concatenates two lists in a zigzag pattern. Args: list1 (List[int]): The first list. list2 (List[int]): T...
code_exercise_27k
7,106
Write a Python function to check if a given key exists in a dictionary and, if it does, return the value associated with that key. If the key does not exist, return a default value provided by the user. The function should handle cases where the dictionary or the key is `None`. 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 Any, Optional def get_value_or_default(dictionary: Optional[dict], key: Any, default: Any) -> Any: """ Check if a given key exists in a dictionary and return its value. If the key does not exist, return a def...
code_exercise_27k
7,109
Write a Python function to concatenate a list with itself, but with the elements reversed. The function should take a list as input and return a new list that is the concatenation of the original list with its reversed version. The code should start with: ```python from typing import List def reverse_concatenate(lst: ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def reverse_concatenate(lst: List) -> List: """ Concatenate a list with itself, but with the elements reversed. Args: lst (List): The input list which will be reversed and concatenated. ...
code_exercise_27k
7,110
Write a Python function to count the total number of items in a nested dictionary. A nested dictionary is a dictionary where values can be either another dictionary or a list of dictionaries. The function should recursively count all items, including those in nested dictionaries and lists. The code should start with: ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Union, List, Dict def count_nested_items(dictionary: Union[Dict, List]) -> int: """ Count the total number of items in a nested dictionary or list of dictionaries. Args: dictionary (Union[Dict, L...
code_exercise_27k
7,113
Write a Python function to calculate the number of minutes between two given timestamps. The timestamps are provided as strings in the format 'YYYY-MM-DD HH:MM:SS'. The function should handle the conversion of the timestamps to datetime objects, compute the difference between them, and return the difference in minutes ...
Here is the Python code to solve the given problem in the markdown block: ```python import datetime def calculate_minutes_between_timestamps(start_timestamp: str, end_timestamp: str) -> int: """ Calculate the number of minutes between two given timestamps. Args: start_timestamp (str): The start ti...
code_exercise_27k
7,114
Write a Python function to concatenate a list with itself, but with every alternate element removed from the second instance of the list. The function should handle lists of any type of elements. The code should start with: ```python from typing import List, Any def concatenate_with_alternate_elements_removed(lst: Lis...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Any def concatenate_with_alternate_elements_removed(lst: List[Any]) -> List[Any]: """ Concatenates a list with itself, but with every alternate element removed from the second instance of the list. ...
code_exercise_27k
7,116
Write a Python function to calculate the number of hours between two given timestamps. The timestamps are provided as strings in the format 'YYYY-MM-DD HH:MM:SS'. The function should return the number of hours as an integer. The code should start with: ```python from datetime import datetime def calculate_hours(start...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import datetime def calculate_hours(start_timestamp: str, end_timestamp: str) -> int: """ Calculates the number of hours between two timestamps. Args: start_timestamp (str): The start timestamp in the...
code_exercise_27k
7,117
Write a Python function to determine the highest and lowest values in a given dictionary. The function should return a tuple containing the highest and lowest values found in the dictionary. If the dictionary is empty, the function should raise a `ValueError`. The code should start with: ```python def find_max_min_val...
Here is the Python code to solve the given problem in the markdown block: ```python def find_max_min_values(dictionary: dict) -> tuple: """ Determine the highest and lowest values in a given dictionary. Args: dictionary (dict): The dictionary to be processed. Returns: tuple: A tuple co...
code_exercise_27k
7,118
Write a Python function to concatenate a given list with itself, but with the first and last elements of the original list swapped before concatenation. If the list has fewer than two elements, it should return the list as is. The function should be named `concat_with_swap` and 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 concat_with_swap(lst: List[int]) -> List[int]: """ Concatenates a list with itself, but with the first and last elements of the original list swapped before concatenation. Args: lst (Lis...
code_exercise_27k
7,119
Write a Python function to concatenate two lists such that the second list is reversed before concatenation. The function should handle lists of any length, including empty lists. The code should start with: ```python from typing import List def concatenate_with_reverse(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 concatenate_with_reverse(list1: List[int], list2: List[int]) -> List[int]: """ Concatenates two lists such that the second list is reversed before concatenation. Args: list1 (List[int]):...
code_exercise_27k
7,122
Write a Python function to merge multiple dictionaries into a single dictionary. The function should accept a variable number of dictionaries as arguments and return a new dictionary that contains all the key-value pairs from the input dictionaries. If there are duplicate keys, the value from the last dictionary in the...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Any def merge_dicts(*dicts: Dict[Any, Any]) -> Dict[Any, Any]: """ Merge multiple dictionaries into a single dictionary. Args: *dicts: A variable number of dictionaries to be merged. R...
code_exercise_27k
7,123
Write a Python function to concatenate two lists, interchanging the second element of the first list with the second element of the second list. If either list is shorter than two elements, the function should raise a `ValueError`. The function should return the concatenated list. 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 concatenate_lists(list1: List[int], list2: List[int]) -> List[int]: """ Concatenates two lists, interchanging the second element of the first list with the second element of the second list. Arg...
code_exercise_27k
7,124
Write a Python function to create a multi-dimensional list with given dimensions and fill it with random values. The function should handle any number of dimensions and ensure that each element in the list is a random floating-point number between 0 and 1. The code should start with: ```python from typing import List i...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List import random def create_multi_dimensional_list(dimensions: List[int]) -> List: """ Create a multi-dimensional list with the given dimensions and fill it with random values. Args: dimensions...
code_exercise_27k
7,127
Write a Python function to concatenate two lists such that the first element of the first list becomes the first element of the result, and the last element of the second list becomes the last element of the result. The function should handle cases where the lists are empty or have only one element. The code should st...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def concatenate_lists(list1: List[int], list2: List[int]) -> List[int]: """ Concatenates two lists such that the first element of the first list becomes the first element of the result, and the last ...
code_exercise_27k
7,130
Write a Python function to calculate the average value of a dictionary's values. If the dictionary is empty, the function should return `None` instead of raising an exception. The function should handle dictionaries with integer or float values. The code should start with: ```python from typing import Dict, Union, Opti...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Union, Optional def average_dictionary_values(dictionary: Dict[str, Union[int, float]]) -> Optional[float]: """ Calculate the average value of a dictionary's values. Args: dictionary (Dict[...
code_exercise_27k
7,132
Write a Python function to extract all the unique values from a given dictionary and return them as a sorted list. The dictionary may contain nested dictionaries, lists, and other data structures. The function should recursively traverse the dictionary to ensure all unique values are collected. The code should start w...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Any, Dict, List def get_unique_sorted_values(dictionary: Dict[Any, Any]) -> List[Any]: """ Extracts all the unique values from a dictionary, including nested dictionaries, lists, and other data structures, ...
code_exercise_27k
7,149
Write a Python function to concatenate two lists such that each element from the first list is followed by its corresponding index in the second list. If the second list is shorter than the first list, the indices should be appended up to the length of the second list. If the second list is longer, ignore the extra ind...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def concat_lists_with_indices(list1: List[any], list2: List[any]) -> List[any]: """ Concatenates two lists such that each element from the first list is followed by its corresponding index in the se...
code_exercise_27k
7,154
Write a Python function to concatenate two lists such that each element from the first list is repeated based on its corresponding index in the second list. If the second list contains a non-positive integer at any index, the corresponding element from the first list should not be included in the result. The function s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def concatenate_lists(list1: List[str], list2: List[int]) -> List[str]: """ Concatenates two lists such that each element from the first list is repeated based on its corresponding index in the second li...
code_exercise_27k
7,155
Write a Python function to sum the values of two dictionaries if the keys match. If a key exists in only one dictionary, it should be included in the result with its value unchanged. The function should handle dictionaries with integer values. The code should start with: ```python from typing import Dict def sum_dict...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def sum_dicts(dict1: Dict[str, int], dict2: Dict[str, int]) -> Dict[str, int]: """ Sums the values of two dictionaries if the keys match. If a key exists in only one dictionary, it is included in the...
code_exercise_27k
7,158
Write a Python function to concatenate two lists such that each element from the first list is repeated in the resulting list based on the value of the corresponding element in the second list. The function should handle input validation and raise appropriate exceptions if the input does not meet the requirements. The...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def concatenate_lists(list1: List, list2: List) -> List: """ Concatenate two lists such that each element from the first list is repeated in the resulting list based on the value of the correspondin...
code_exercise_27k
7,159
Write a Python function to find the difference between two dictionaries by comparing their keys and values. The function should return a dictionary that contains the differences between the two input dictionaries. The differences should include keys that are present in one dictionary but not the other, as well as keys ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, Any def find_dict_difference(dict1: Dict[Any, Any], dict2: Dict[Any, Any]) -> Dict[Any, Any]: """ Find the difference between two dictionaries by comparing their keys and values. Args: dict...
code_exercise_27k
7,164
Write a Python function to generate all possible combinations of elements from two given lists. Each combination should be formed by concatenating one element from the first list with one element from the second list. The function should return a list of these combinations. The code should start with: ```python from t...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List def combine_lists(list1: List[str], list2: List[str]) -> List[str]: """ Generates all possible combinations of elements from two given lists by concatenating each element from the first list with each el...
code_exercise_27k
7,165
Write a Python function to sort a dictionary based on its values in descending order. The function should return a new dictionary with the same keys but sorted by their corresponding values in descending order. The code should start with: ```python from typing import Dict def sort_dict_by_value_desc(dictionary: Dict[s...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict def sort_dict_by_value_desc(dictionary: Dict[str, int]) -> Dict[str, int]: """ Sorts a dictionary based on its values in descending order. Args: dictionary (Dict[str, int]): The dictionary t...
code_exercise_27k
7,169
Write a Python function to find the top n keys with the highest values in a given dictionary. The function should return a list of these keys sorted in descending order based on their values. If n is greater than the number of keys in the dictionary, the function should return all keys sorted by their values. The funct...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import Dict, List def get_top_n_keys(dictionary: Dict[str, int], n: int) -> List[str]: """ Returns the top n keys with the highest values in the given dictionary. Args: dictionary (Dict[str, int]): The ...
code_exercise_27k
7,179
Write a Python function to extract unique keys from a list of dictionaries and create a new dictionary with those keys. The new dictionary should have the extracted keys as its keys and `None` as its values. The function should handle dictionaries with different keys and ensure that each key is unique in the resulting ...
Here is the Python code to solve the given problem in the markdown block: ```python from typing import List, Dict def extract_unique_keys(list_of_dicts: List[Dict[str, any]]) -> Dict[str, None]: """ Extracts unique keys from a list of dictionaries and creates a new dictionary with those keys. Args: ...
code_exercise_27k
7,181
Write a Python function to sort a list of integers in descending order using a custom sorting algorithm. The function should implement a merge sort algorithm to achieve this. The code should start with: ```python from typing import List def sort_integers_descending(numbers: List[int]) -> List[int]: ```
Here is the Python code to solve the given problem in the markdown block: : ```python from typing import List def sort_integers_descending(numbers: List[int]) -> List[int]: """ Sorts a list of integers in descending order using a merge sort algorithm. Args: numbers (List[int]): The list of integer...
code_exercise_27k
7,182
Write a Python function to find the date after a certain number of days from a given date. The function should handle both positive and negative day increments. The input date should be in the format 'YYYY-MM-DD', and the output date should also be in the same format. The code should start with: ```python from datetim...
Here is the Python code to solve the given problem in the markdown block: ```python from datetime import datetime, timedelta def add_days_to_date(date_string: str, days: int) -> str: """ Add a certain number of days to a given date and return the resulting date. Args: date_string (str): A string r...