Appearance
question:# Problem Statement You are given a problem involving the calculation of the final amount of money in a savings account given an initial principal, annual interest rate, and the number of years the money is invested or saved. Interest is compounded annually. The formula to calculate the final amount ( A ) after ( t ) years with an annual interest rate ( r ) (expressed as a decimal) and an initial principal ( P ) is: [ A = P cdot (1 + r)^t ] where: - ( P ) is the initial principal in dollars. - ( r ) is the annual interest rate in decimal form. - ( t ) is the time in years. # Task Write a function named `calculate_savings` that takes three parameters: 1. `principal` (float): initial principal in dollars. Must be non-negative. 2. `annual_rate` (float): annual interest rate in decimal form. Must be non-negative. 3. `years` (int): the number of years the money is invested or saved. Must be non-negative. The function should return the final amount in the savings account rounded to two decimal places. # Input and Output Format * **Input**: - A float `principal`: The initial amount of money. - A float `annual_rate`: The annual interest rate in decimal form. - An int `years`: The number of years the money is invested. * **Output**: - A float representing the final amount in the savings account rounded to two decimal places. # Constraints - The `principal` and `annual_rate` must be non-negative. - The `years` must be a non-negative integer. If any of the constraints are violated, the function should raise a `ValueError` with an appropriate error message. # Example ```python def calculate_savings(principal: float, annual_rate: float, years: int) -> float: # Your code here # Example Usage print(calculate_savings(1000.0, 0.05, 10)) # Returns 1628.89 print(calculate_savings(500, 0.03, 5)) # Returns 579.64 ``` # Notes 1. Your implementation should make use of the built-in `**` operator to perform the exponentiation. 2. Ensure your function handles all edge cases as specified, raising `ValueError` for invalid inputs.
answer:def calculate_savings(principal: float, annual_rate: float, years: int) -> float: if principal < 0: raise ValueError("Principal must be non-negative.") if annual_rate < 0: raise ValueError("Annual rate must be non-negative.") if years < 0: raise ValueError("Years must be non-negative.") final_amount = principal * (1 + annual_rate) ** years return round(final_amount, 2)
question:# Question: Minimum Moves to Reach End of Maze You are required to implement a function that calculates the minimum number of moves required to reach the end of a given maze from the start position. The maze is represented as a 2D grid where each cell can either be empty (0) or blocked (1). You can move up, down, left, or right from a cell, but you cannot move diagonally, and you cannot move through a blocked cell. The grid is given as an `n x m` list of lists. The start position is always at the top-left corner of the grid (0, 0), and the goal is to reach the bottom-right corner of the grid (n-1, m-1). __Requirements:__ * If it is not possible to reach the bottom-right corner from the top-left corner, return -1. * Ensure the function computes results efficiently even for larger grids. * Implement the function using a breadth-first search (BFS) method to achieve optimal time complexity. __Function Signature:__ ```python def min_moves_to_end(maze: List[List[int]]) -> int: pass ``` __Input:__ * A list of lists `maze` of integers, representing the grid. __Output:__ * Return the minimum number of moves required to reach the bottom-right corner or -1 if it is not possible. __Constraints:__ * The input `maze` will be a non-empty list of lists containing only 0s and 1s, and will always be rectangular. * The dimensions of the grid are limited to `1 <= n, m <= 1000`. __Example:__ ```python assert min_moves_to_end([[0, 0, 1], [0, 1, 0], [0, 0, 0]]) == 4 assert min_moves_to_end([[0, 1], [1, 0]]) == -1 assert min_moves_to_end([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) == 4 assert min_moves_to_end([[0, 0, 1, 0, 0], [0, 1, 0, 1, 0], [0, 0, 0, 0, 0], [1, 1, 0, 1, 0], [0, 0, 0, 0, 0]]) == 8 ``` __Explanation:__ * For the first example, the path is (0,0) -> (1,0) -> (2,0) -> (2,1) -> (2,2). * For the second example, it is impossible to reach the end, hence -1. * For the third example, the path can be multiple different ways, e.g., (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2).
answer:from typing import List def min_moves_to_end(maze: List[List[int]]) -> int: from collections import deque # Edge case: checking if the start or end is blocked if maze[0][0] == 1 or maze[-1][-1] == 1: return -1 n, m = len(maze), len(maze[0]) directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] # Up, Down, Left, Right queue = deque([(0, 0, 0)]) # (row, col, distance) visited = set((0, 0)) while queue: row, col, dist = queue.popleft() if row == n - 1 and col == m - 1: return dist for dr, dc in directions: r, c = row + dr, col + dc if 0 <= r < n and 0 <= c < m and maze[r][c] == 0 and (r, c) not in visited: visited.add((r, c)) queue.append((r, c, dist + 1)) return -1
question:# Warehouse Robot Path Planning You are tasked with programming a simple robot to navigate a warehouse. The robot starts at a specific position within a 2D grid warehouse and must move to the target position while avoiding obstacles. The warehouse layout is represented as a matrix where empty cells are denoted by 0, obstacles by 1, the robot's start position by 'S', and the target position by 'T'. **Goal**: Implement a function `find_path` that finds a path from the start position to the target position without colliding with obstacles. If there is no valid path, return an empty list. The robot can move up, down, left, or right, but not diagonally. # Function Signature ```python def find_path(warehouse: list[list[int]], start: tuple[int, int], target: tuple[int, int]) -> list[tuple[int, int]]: pass ``` # Input * **warehouse** (list of list of int) - A 2D grid representing the warehouse. * **start** (tuple of int) - The starting coordinates of the robot (row, column). * **target** (tuple of int) - The target coordinates for the robot (row, column). # Output * **path** (list of tuple) - A list of coordinates representing the path from start to target. Each coordinate should be a tuple (row, column). If there is no valid path, return an empty list. # Constraints * 2 <= len(warehouse), len(warehouse[0]) <= 100 * 0 <= start[0], start[1], target[0], target[1] < length of the respective dimensions * The start and target positions do not contain obstacles. # Example ```python warehouse = [ [0, 0, 0, 0], [1, 1, 0, 1], [0, 0, 0, 0], [0, 1, 1, 0], [0, 0, 0, 0] ] start = (0, 0) target = (4, 3) result = find_path(warehouse, start, target) print(result) # Possible Output: # [(0, 0), (0, 1), (0, 2), (0, 3), (1, 2), (2, 2), (2, 3), (3, 3), (4, 3)] ``` # Notes * Ensure the robot does not move outside the boundaries of the warehouse. * Use Breadth-First Search (BFS) for finding the shortest path. * Multiple valid paths may exist; your function only needs to return one of them. * Careful consideration of edge cases, such as fully obstructed paths, should be handled gracefully by returning an empty list.
answer:def find_path(warehouse, start, target): from collections import deque rows, cols = len(warehouse), len(warehouse[0]) directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] def is_valid(r, c): return 0 <= r < rows and 0 <= c < cols and warehouse[r][c] == 0 queue = deque([(start, [start])]) visited = set([start]) while queue: (current_r, current_c), path = queue.popleft() if (current_r, current_c) == target: return path for dr, dc in directions: new_r, new_c = current_r + dr, current_c + dc if is_valid(new_r, new_c) and (new_r, new_c) not in visited: visited.add((new_r, new_c)) queue.append(((new_r, new_c), path + [(new_r, new_c)])) return []
question:# Coding Assessment Question Problem Description: You are tasked with implementing a function `find_mex(arr: List[int]) -> int`. This function should find the "minimum excludant" (MEX) of a given list of non-negative integers. The MEX of a set of integers is the smallest non-negative integer that is not present in the set. Detailed Requirements: 1. **Function Signature**: `def find_mex(arr: List[int]) -> int:` 2. **Inputs**: - `arr`: a list of non-negative integers (0 ≤ arr[i] ≤ 10^6) and the length of the list (1 ≤ len(arr) ≤ 10^6). 3. **Output**: - An integer representing the MEX of the given list. 4. **Constraints**: - Ensure the function works within reasonable time and space limits. # Example: ```python >>> find_mex([1, 0, 2, 4, 3]) 5 >>> find_mex([2, 3, 1, 0]) 4 >>> find_mex([0, 1, 2, 3]) 4 >>> find_mex([1, 2, 3, 4]) 0 ``` # Notes: 1. The function should handle large inputs efficiently. 2. Consider edge case scenarios such as: - The input list containing all consecutive numbers starting from 0. - The input list having large gaps. - Lists where the smallest number missing is not at the beginning or end. 3. The solution should not involve sorting the array since the time complexity needs to be optimal. --- Good luck! Ensure your solution meets the optimal time and space complexity as discussed, and handles edge cases appropriately.
answer:from typing import List def find_mex(arr: List[int]) -> int: Finds the minimum excludant (MEX) of a given list of non-negative integers. The MEX of a set of integers is the smallest non-negative integer that is not present in the set. # Create a set of the input list for O(1) average time complexity lookups. num_set = set(arr) # Start checking from 0 and find the smallest number not in the set. mex = 0 while mex in num_set: mex += 1 return mex