Appearance
question:# Evaluate Loan Eligibility Based on Credit Score and Income Problem Description: You are tasked with creating a function to determine loan eligibility based on the applicant's credit score and annual income. Criteria: 1. A credit score of 700 or above is required for consideration. 2. A minimum annual income of 30,000 is required. 3. If both conditions are met, the applicant is eligible for the loan. Otherwise, they are not. Function Signature: ```python def is_loan_eligible(credit_score: int, annual_income: float) -> bool: pass ``` Input: * An integer `credit_score` representing the applicant's credit score. (0 <= credit_score <= 850) * A float `annual_income` representing the applicant's annual income in dollars. (0 <= annual_income <= 1,000,000) Output: * A boolean `True` if the applicant meets both conditions, otherwise `False`. Constraints: * `credit_score` must be between 0 and 850 inclusive. * `annual_income` must be between 0 and 1,000,000 dollars inclusive. Examples: * **Example 1**: ```python is_loan_eligible(credit_score=750, annual_income=45000) ``` **Output**: ```python True ``` * **Example 2**: ```python is_loan_eligible(credit_score=680, annual_income=55000) ``` **Output**: ```python False ``` * **Example 3**: ```python is_loan_eligible(credit_score=720, annual_income=25000) ``` **Output**: ```python False ``` * **Example 4**: ```python is_loan_eligible(credit_score=815, annual_income=95000) ``` **Output**: ```python True ``` Notes: * The function should raise a `ValueError` if either `credit_score` or `annual_income` is outside the given range. Implement the `is_loan_eligible` function to evaluate loan eligibility according to the specified criteria.
answer:def is_loan_eligible(credit_score: int, annual_income: float) -> bool: Determines loan eligibility based on credit score and annual income. Args: - credit_score (int): The applicant's credit score. - annual_income (float): The applicant's annual income. Returns: - bool: True if eligible, otherwise False. # Validate input ranges if not (0 <= credit_score <= 850): raise ValueError("Credit score must be between 0 and 850.") if not (0 <= annual_income <= 1_000_000): raise ValueError("Annual income must be between 0 and 1,000,000 dollars.") # Check loan eligibility criteria return credit_score >= 700 and annual_income >= 30_000
question:# Binary Search Tree Implementation with Balancing Problem Statement: You are tasked with implementing a Binary Search Tree (BST) that supports dynamic balancing using the AVL tree rotation techniques. The tree should maintain its height-balanced property with every insertion and deletion operation to ensure efficient execution of lookup, insert, and delete operations. Requirements: 1. **Function Signature**: ```python class AVLTree: def __init__(self) -> None: def insert(self, key: int) -> None: def delete(self, key: int) -> None: def find(self, key: int) -> bool: def inorder_traversal(self) -> List[int]: def __repr__(self) -> str: ``` 2. **Input and Output Format**: - `insert(self, key: int)`: Inserts a given key into the AVL tree while ensuring the tree remains balanced. - `delete(self, key: int)`: Removes a given key from the AVL tree while ensuring the tree remains balanced. - `find(self, key: int)`: Returns `True` if the key is present in the AVL tree, otherwise `False`. - `inorder_traversal(self)`: Returns a list of keys in the AVL tree in in-order traversal. - `__repr__(self)`: Returns a string representation of the AVL tree. 3. **Constraints**: - Key type is an integer. - Ensure the AVL tree maintains its balance property (i.e., for any node, the heights of the left and right subtrees differ by at most one). - Implement the necessary tree rotation mechanisms (left rotation, right rotation, left-right rotation, and right-left rotation) to keep the tree balanced. 4. **Performance Requirements**: - Ensure the AVL tree operations (insert, delete, and find) have a logarithmic time complexity of O(log n). Example Usage: ```python # Initializing AVL tree avl_tree = AVLTree() # Inserting elements avl_tree.insert(10) avl_tree.insert(20) avl_tree.insert(5) avl_tree.insert(4) avl_tree.insert(6) # Checking tree balance print(avl_tree) # Output: AVLTree(In-order: [4, 5, 6, 10, 20]) # In order traversal print(avl_tree.inorder_traversal()) # Output: [4, 5, 6, 10, 20] # Finding elements print(avl_tree.find(10)) # Output: True print(avl_tree.find(15)) # Output: False # Deleting an element avl_tree.delete(20) # Checking tree balance print(avl_tree) # Output: AVLTree(In-order: [4, 5, 6, 10]) ``` Implement the `AVLTree` class to fulfill the above specifications.
answer:class AVLTreeNode: def __init__(self, key): self.key = key self.left = None self.right = None self.height = 1 class AVLTree: def __init__(self): self.root = None def insert(self, key): if not self.root: self.root = AVLTreeNode(key) else: self.root = self._insert(self.root, key) def _insert(self, node, key): if not node: return AVLTreeNode(key) if key < node.key: node.left = self._insert(node.left, key) else: node.right = self._insert(node.right, key) node.height = 1 + max(self._get_height(node.left), self._get_height(node.right)) return self._balance(node) def delete(self, key): if not self.root: return else: self.root = self._delete(self.root, key) def _delete(self, node, key): if not node: return node if key < node.key: node.left = self._delete(node.left, key) elif key > node.key: node.right = self._delete(node.right, key) else: if not node.left: return node.right elif not node.right: return node.left temp = self._get_min_value_node(node.right) node.key = temp.key node.right = self._delete(node.right, temp.key) node.height = 1 + max(self._get_height(node.left), self._get_height(node.right)) return self._balance(node) def find(self, key): return self._find(self.root, key) def _find(self, node, key): if not node: return False if key == node.key: return True elif key < node.key: return self._find(node.left, key) else: return self._find(node.right, key) def inorder_traversal(self): result = [] self._inorder_traversal(self.root, result) return result def _inorder_traversal(self, node, result): if not node: return self._inorder_traversal(node.left, result) result.append(node.key) self._inorder_traversal(node.right, result) def __repr__(self): return f"AVLTree(In-order: {self.inorder_traversal()})" def _balance(self, node): balance_factor = self._get_balance(node) if balance_factor > 1: if self._get_balance(node.left) < 0: node.left = self._rotate_left(node.left) return self._rotate_right(node) if balance_factor < -1: if self._get_balance(node.right) > 0: node.right = self._rotate_right(node.right) return self._rotate_left(node) return node def _rotate_right(self, y): x = y.left T2 = x.right x.right = y y.left = T2 y.height = 1 + max(self._get_height(y.left), self._get_height(y.right)) x.height = 1 + max(self._get_height(x.left), self._get_height(x.right)) return x def _rotate_left(self, x): y = x.right T2 = y.left y.left = x x.right = T2 x.height = 1 + max(self._get_height(x.left), self._get_height(x.right)) y.height = 1 + max(self._get_height(y.left), self._get_height(y.right)) return y def _get_height(self, node): if not node: return 0 return node.height def _get_min_value_node(self, node): current = node while current.left: current = current.left return current def _get_balance(self, node): if not node: return 0 return self._get_height(node.left) - self._get_height(node.right)
question:Implementing a Basic Priority Queue You are tasked to design and implement a basic Priority Queue data structure using a binary heap in Python. This priority queue will allow for elements to be added and removed based on their priority, with the highest priority element being removed first. Priorities are defined using integer values, where a smaller integer indicates a higher priority. Description Implement a class `PriorityQueue` that supports the following methods: 1. `insert`: Inserts an element into the priority queue with an associated priority. 2. `remove`: Removes and returns the element with the highest priority. 3. `peek`: Retrieves, without removing, the element with the highest priority. 4. `is_empty`: Checks if the priority queue is empty. Requirements - Elements are stored in a binary heap where the element with the smallest priority value is always at the root. - Use a list to implement the binary heap, with the root element at index 0. - Ensure all methods adhere to the time complexity constraints of binary heap operations. Class Signature ```python class PriorityQueue: def __init__(self): pass def insert(self, element: Any, priority: int) -> None: pass def remove(self) -> Any: pass def peek(self) -> Any: pass def is_empty(self) -> bool: pass ``` Parameters: - The `element` parameter in the `insert` method can be of any type (`Any`). - The `priority` parameter in the `insert` method is an `int`. - `remove` and `peek` methods return the element with the highest priority. - `is_empty` method returns `True` if the priority queue is empty and `False` otherwise. Example Use Case: ```python >>> pq = PriorityQueue() >>> pq.insert('task1', 3) >>> pq.insert('task2', 1) >>> pq.insert('task3', 2) >>> pq.peek() 'task2' >>> pq.remove() 'task2' >>> pq.remove() 'task3' >>> pq.is_empty() False >>> pq.remove() 'task1' >>> pq.is_empty() True ``` Constraints: - Each method in the class must operate within O(log n) time complexity for insert and remove methods due to heap operations. - `peek` and `is_empty` methods should operate in O(1) time complexity. This question assesses the candidate's ability to implement a fundamental data structure and utilize binary heap properties effectively.
answer:import heapq class PriorityQueue: def __init__(self): self.heap = [] def insert(self, element, priority): heapq.heappush(self.heap, (priority, element)) def remove(self): if self.is_empty(): raise IndexError("remove from empty priority queue") return heapq.heappop(self.heap)[1] def peek(self): if self.is_empty(): raise IndexError("peek from empty priority queue") return self.heap[0][1] def is_empty(self): return len(self.heap) == 0
question:# Question: Implement a Cache with Expiration Policy You are tasked with creating a simple in-memory cache that supports basic operations like insertion, retrieval, and deletion of entries, along with an automatic expiration policy for cache entries. **Function Signatures:** ```python class Cache: def __init__(self): # Your code here def set(self, key: str, value: Any, ttl: int) -> None: # Your code here def get(self, key: str) -> Any: # Your code here def delete(self, key: str) -> None: # Your code here ``` # Input Format - The `set` function accepts three parameters: a string `key`, a value of any type, and an integer `ttl` (time-to-live in seconds). - The `get` function accepts a single string `key` and returns the corresponding value if it exists and has not expired; otherwise, it returns `None`. - The `delete` function accepts a single string `key` and removes the entry from the cache. # Constraints - Ensure the expired entries are not retrievable. - Manage the cache efficiently, updating entries' expiration statuses appropriately. # Example ```python cache = Cache() cache.set("a", 1, 10) # Set key "a" with value 1 and TTL of 10 seconds import time time.sleep(5) assert cache.get("a") == 1 # Value is still valid time.sleep(6) assert cache.get("a") is None # Value has expired cache.set("b", 2, 5) # Set key "b" with value 2 and TTL of 5 seconds time.sleep(3) cache.delete("b") assert cache.get("b") is None # Key "b" was deleted before expiration ``` # Notes - Implement the cache using any efficient data structures of your choice. - Handle edge cases such as setting values with zero or negative TTLs appropriately (e.g., consider them as immediate expiration). This question tests your ability to handle stateful data structures, time-based policies, and efficient data access patterns in addition to typical insertion and deletion operations.
answer:import time from typing import Any, Dict, Optional class Cache: def __init__(self): # Dictionary to hold the cache data self.store: Dict[str, Any] = {} # Dictionary to hold the expiration times self.expirations: Dict[str, float] = {} def set(self, key: str, value: Any, ttl: int) -> None: Sets a key with a given value and time-to-live (ttl). self.store[key] = value # Set the expiration time as current time + ttl self.expirations[key] = time.time() + ttl def get(self, key: str) -> Optional[Any]: Retrieves the value for a given key if it exists and has not expired. Returns None if the key does not exist or has expired. if key in self.store: if time.time() < self.expirations.get(key, 0): return self.store[key] else: # Item has expired, remove it self.delete(key) return None else: return None def delete(self, key: str) -> None: Deletes a given key from the cache. if key in self.store: del self.store[key] if key in self.expirations: del self.expirations[key]