Skip to content
🤔prompts chat🧠
🔍
question:# Problem Statement You are developing a function to track the monthly expenses for a user. Each expense is categorized into specific types, and the function needs to determine the total expenditure for each category over a given period. Write a function named `calculate_monthly_expenses` that takes a list of tuples where each tuple consists of a string representing the category and an integer representing the amount spent in that category. The function should return a dictionary where each key is a category and the value is the total amount spent in that category. # Input * `expenses` (list of tuples): A list where each tuple contains: * a string representing the category (e.g., "Food", "Transportation", "Entertainment", etc.). * an integer representing the expense amount in that category. # Output * A dictionary where each key is a category (string) and the value is the total amount spent (integer) in that category. # Examples ```python # Example 1 assert calculate_monthly_expenses([("Food", 200), ("Transportation", 50), ("Food", 150), ("Entertainment", 100)]) == {"Food": 350, "Transportation": 50, "Entertainment": 100} # Example 2 assert calculate_monthly_expenses([("Groceries", 100), ("Bills", 200), ("Groceries", 50), ("Bills", 300)]) == {"Groceries": 150, "Bills": 500} # Example 3 assert calculate_monthly_expenses([("Utilities", 75), ("Transport", 25)]) == {"Utilities": 75, "Transport": 25} # Example 4 assert calculate_monthly_expenses([("Rent", 500), ("Rent", 500), ("Rent", 500)]) == {"Rent": 1500} # Example 5 assert calculate_monthly_expenses([]) == {} ``` # Constraints * Each expense amount is a non-negative integer. * The list of expenses will contain no more than 10^4 entries. * Each category string will be non-empty and have a maximum length of 50 characters. * The total amount for any category will not exceed 10^7. # Performance Requirements * The algorithm should efficiently process the expense list with a linear time complexity, O(n), where n is the number of expenses. # Additional Notes * If the input list is empty, the function should return an empty dictionary. * The function should handle cases where multiple expenses belong to the same category and sum their amounts correctly.

answer:def calculate_monthly_expenses(expenses): Calculates the total expenses for each category. Parameters: expenses (list of tuples): A list where each tuple contains a category (string) and an amount spent (integer). Returns: dict: A dictionary where each key is a category and the value is the total amount spent in that category. expense_dict = {} for category, amount in expenses: if category in expense_dict: expense_dict[category] += amount else: expense_dict[category] = amount return expense_dict

question:# Problem Statement A company wants to analyze their employees' working hours and identify those who are eligible for an overtime bonus. The criterion for eligibility is that an employee has worked more than 40 hours in a week. You are given the working hours of employees for a given week in the form of a list of tuples. Each tuple contains an employee ID (integer) and the total number of hours they worked in that week (integer). Your task is to write a function `find_overtime_employees` that returns a list of employee IDs who are eligible for the overtime bonus. Function Signature ```python def find_overtime_employees(hours: List[Tuple[int, int]]) -> List[int]: pass ``` Input * `hours` (List[Tuple[int, int]]): A list of tuples where each tuple contains an integer `employee_id` and an integer `worked_hours` (1 <= len(hours) <= 1000, 1 <= employee_id <= 100000, 0 <= worked_hours <= 168). Output * A list of integers representing the IDs of employees who worked more than 40 hours in the given week. Example ```python assert find_overtime_employees([(1, 45), (2, 38), (3, 50), (4, 40), (5, 42)]) == [1, 3, 5] assert find_overtime_employees([(1, 35), (2, 38), (3, 40), (4, 30), (5, 28)]) == [] ``` Constraints * Consider edge cases such as when no employee works more than 40 hours or when all employees work more than 40 hours. # Additional Context Ensure your solution is efficient and handles large input sizes effectively.

answer:from typing import List, Tuple def find_overtime_employees(hours: List[Tuple[int, int]]) -> List[int]: Returns a list of employee IDs who worked more than 40 hours in the given week. overtime_employees = [] for employee_id, worked_hours in hours: if worked_hours > 40: overtime_employees.append(employee_id) return overtime_employees

question:# Coding Question Scenario In the field of data analytics, it's important to identify sections of a dataset where significant changes occur. One common method is to detect "local peaks" in a sequence of numbers, where a number is considered a peak if it is larger than its immediate neighbors. Task Implement the function `find_local_peaks` to identify all the local peaks in a list of numerical data points. # Function Signature ```python def find_local_peaks(data: list[int]) -> list[int]: ``` # Input * `data`: A list of integers representing the data points. # Output * A list of integers representing the positions (indices) of the local peaks in the input data. # Constraints * The length of `data` will be between 3 and 10^5. * Each element in `data` will be an integer. # Requirements 1. A local peak is defined as an element that is strictly greater than its neighbors. 2. The first and last elements of the list cannot be local peaks since they do not have both neighbors. # Example ```python # Input data = [1, 3, 7, 1, 2, 6, 3, 2, 9, 5] # Output [2, 5, 8] ``` **Notes:** - Use 0-based indexing to indicate positions. - Ensure efficiency to handle large datasets within the given constraints. **Edge cases to consider:** - Sequences with no local peaks. - Handling instances where multiple peaks occur consecutively. - The shortest possible valid input with exactly three elements.

answer:def find_local_peaks(data: list[int]) -> list[int]: peaks = [] # Iterate from the second element to the second last element for i in range(1, len(data) - 1): if data[i] > data[i - 1] and data[i] > data[i + 1]: peaks.append(i) return peaks

question:# Coding Assessment Question Context: A fundamental task in programming is to determine the frequency of unique elements in a list. This time, we extend this concept to handle more complex data structures by incorporating both lists and dictionaries within a nested structure. Task: Write a function `count_unique_elements(data: list | dict) -> dict` that counts the frequency of unique elements within a nested list and dictionary structure. Your function should handle any level of nesting and return a dictionary where the keys are the unique elements, and the values are their respective frequencies. Input: * A list or dictionary, `data`, which can contain integers, strings, floats, other lists, or dictionaries nested within each other. Output: * A dictionary representing the frequency of each unique integer, string, or float in the input structure. Constraints: * The data structure can be deeply nested. * The elements can be integers, strings, floats, lists, or dictionaries containing these types. * The structure may contain mixed types and elements. Performance Requirements: * Aim for an O(n) time complexity where n is the total number of elements in the nested structure. * Space complexity should be minimized based on the nesting depth. Example: ```python def count_unique_elements(data: list | dict) -> dict: # Your implementation here # Test cases print(count_unique_elements([1, 2, [3, 1], {"a": 2, "b": [1]}])) # Output: {1: 3, 2: 2, 3: 1} print(count_unique_elements({"x": 1.1, "y": {"z": [1.1, 2.2]}})) # Output: {1.1: 2, 2.2: 1} print(count_unique_elements([{"a": "apple", "b": ["banana", "apple"]}, "banana", "cat"])) # Output: {"apple": 2, "banana": 2, "cat": 1} ``` Note: * Carefully consider the data structure's nested nature and ensure a robust solution. * Think through edge cases such as mixed nested empty structures, although elements within the structure are assumed to be present in minimal cases for the problem's validity. * The function should correctly iterate through the mixed and arbitrarily nested data hierarchy.

answer:def count_unique_elements(data): Recursively counts the frequency of unique elements in a nested list or dictionary. freq_dict = {} def count_elements(elem): if isinstance(elem, (int, float, str)): if elem in freq_dict: freq_dict[elem] += 1 else: freq_dict[elem] = 1 elif isinstance(elem, list): for item in elem: count_elements(item) elif isinstance(elem, dict): for key, value in elem.items(): count_elements(key) count_elements(value) count_elements(data) return freq_dict

Released under the chat License.

has loaded