Skip to content
🤔prompts chat🧠
🔍
question:# Question: Inventory Management System for a Warehouse Context You are developing an inventory management system for a warehouse. This system needs to keep track of the items in stock and manage inventory operations such as adding new items, updating existing items, and retrieving item information. Task Implement a Python class `Inventory` that manages the inventory in a warehouse with the following methods: 1. `add_item(name: str, quantity: int, price: float) -> None`: Adds a new item to the inventory. If the item already exists, increment its quantity by the given amount and update its price. 2. `update_item(name: str, quantity: int, price: float) -> None`: Updates the quantity and price of an existing item. If the item does not exist, raise a `ValueError`. 3. `delete_item(name: str) -> None`: Removes an item from the inventory. If the item does not exist, raise a `ValueError`. 4. `get_item(name: str) -> Tuple[int, float]`: Returns the quantity and price of the given item. If the item does not exist, raise a `ValueError`. Input - Each method will take the necessary parameters as described above. Output - Each method will perform operations according to their description. - The `get_item` method will return a tuple containing the quantity and price of the given item. Constraints 1. All item names will be strings. 2. The quantity will be a non-negative integer. 3. The price will be a non-negative float. 4. Method invocations will follow the required sequence to guarantee valid interactions. Example ```python from typing import Dict, Tuple class Inventory: def __init__(self): self.items: Dict[str, Tuple[int, float]] = {} def add_item(self, name: str, quantity: int, price: float) -> None: if name in self.items: existing_quantity, _ = self.items[name] self.items[name] = (existing_quantity + quantity, price) else: self.items[name] = (quantity, price) def update_item(self, name: str, quantity: int, price: float) -> None: if name in self.items: self.items[name] = (quantity, price) else: raise ValueError("Item does not exist") def delete_item(self, name: str) -> None: if name in self.items: del self.items[name] else: raise ValueError("Item does not exist") def get_item(self, name: str) -> Tuple[int, float]: if name in self.items: return self.items[name] else: raise ValueError("Item does not exist") # Example usage inventory = Inventory() inventory.add_item('apple', 50, 1.2) inventory.add_item('banana', 30, 0.5) print(inventory.get_item('apple')) # Output: (50, 1.2) inventory.update_item('apple', 100, 1.3) print(inventory.get_item('apple')) # Output: (100, 1.3) inventory.delete_item('banana') # print(inventory.get_item('banana')) # Raises ValueError: Item does not exist ``` Notes - Ensure your solution handles cases where operations might involve non-existent items appropriately by raising `ValueError` where specified. - Maintain good coding practices by ensuring the class methods perform the specified tasks efficiently.

answer:from typing import Dict, Tuple class Inventory: def __init__(self): self.items: Dict[str, Tuple[int, float]] = {} def add_item(self, name: str, quantity: int, price: float) -> None: if name in self.items: existing_quantity, _ = self.items[name] self.items[name] = (existing_quantity + quantity, price) else: self.items[name] = (quantity, price) def update_item(self, name: str, quantity: int, price: float) -> None: if name in self.items: self.items[name] = (quantity, price) else: raise ValueError("Item does not exist") def delete_item(self, name: str) -> None: if name in self.items: del self.items[name] else: raise ValueError("Item does not exist") def get_item(self, name: str) -> Tuple[int, float]: if name in self.items: return self.items[name] else: raise ValueError("Item does not exist")

question:# Cache System Design In this task, you will be required to design and implement a custom cache system with two different types of cache policies: Least Recently Used (LRU) and First In, First Out (FIFO). There are two parts to this task: Part A: LRUCache Implement a cache system with the Least Recently Used (LRU) policy. Create a class `LRUCache` that includes the following methods: 1. `__init__(self, capacity: int)`: Initializes the cache with a given capacity. 2. `put(self, key: int, value: int)`: Inserts a key-value pair into the cache. If the cache reaches its capacity, it removes the least recently used item. 3. `get(self, key: int) -> int`: Fetches the value associated with the key. If the key is not found, return `-1`. 4. `__str__(self) -> str`: Returns a string representation of the cache's current state. Part B: FIFOCache Implement a cache system with the First In, First Out (FIFO) policy. Create a class `FIFOCache` that includes the following methods: 1. `__init__(self, capacity: int)`: Initializes the cache with a given capacity. 2. `put(self, key: int, value: int)`: Inserts a key-value pair into the cache. If the cache reaches its capacity, it removes the oldest inserted item. 3. `get(self, key: int) -> int`: Fetches the value associated with the key. If the key is not found, return `-1`. 4. `__str__(self) -> str`: Returns a string representation of the cache's current state. # Input and Output * `put(key, value)` accepts an integer key and value. * `get(key)` accepts a single key and returns the associated value. * Both classes should handle standard caching operations efficiently. # Performance Requirements Ensure that your implementation meets the specified time complexities: * Insertions and updates (`put`): O(1) * Retrievals (`get`): O(1) * String representation should be efficient. # Example ```python # Part A: LRUCache lru_cache = LRUCache(2) lru_cache.put(1, 1) lru_cache.put(2, 2) print(lru_cache) # {1: 1, 2: 2} print(lru_cache.get(1)) # 1 lru_cache.put(3, 3) # LRU key 2 is evicted print(lru_cache) # {1: 1, 3: 3} print(lru_cache.get(2)) # -1 # Part B: FIFOCache fifo_cache = FIFOCache(2) fifo_cache.put(1, 1) fifo_cache.put(2, 2) print(fifo_cache) # {1: 1, 2: 2} print(fifo_cache.get(1)) # 1 fifo_cache.put(3, 3) # FIFO key 1 is evicted print(fifo_cache) # {2: 2, 3: 3} print(fifo_cache.get(2)) # 2 ``` Implement the classes `LRUCache` and `FIFOCache` with the specified methods and ensure your code passes the above examples.

answer:from collections import OrderedDict class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = OrderedDict() def put(self, key: int, value: int): if key in self.cache: self.cache.move_to_end(key) self.cache[key] = value if len(self.cache) > self.capacity: self.cache.popitem(last=False) def get(self, key: int) -> int: if key in self.cache: self.cache.move_to_end(key) return self.cache[key] return -1 def __str__(self) -> str: return str(self.cache) class FIFOCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = OrderedDict() def put(self, key: int, value: int): if key not in self.cache: if len(self.cache) >= self.capacity: self.cache.popitem(last=False) self.cache[key] = value def get(self, key: int) -> int: return self.cache.get(key, -1) def __str__(self) -> str: return str(self.cache)

question:# Coding Assessment Question - Balanced Brackets Scenario: You have been hired to work on the backend of an integrated development environment (IDE). One essential feature the IDE needs is to check if the code written by programmers has balanced brackets. Brackets include parenthesis `()`, square brackets `[]`, and curly braces `{}`. Your task is to write a function that evaluates whether the brackets in a string are balanced or not. Question: **Function Signature:** ```python def are_brackets_balanced(s: str) -> bool: ``` **Input:** * A single string `s` which can contain any characters, including letters, numbers, and special characters. **Output:** * Return `True` if the brackets in `s` are balanced. * Return `False` otherwise. **Constraints:** * The input `s` will have a length up to 10,000 characters. **Examples:** ```python are_brackets_balanced("(a + b) * (c + d)") # Expected output: True are_brackets_balanced("{[()]}") # Expected output: True are_brackets_balanced("{[(a + b) - {c * d}] / e}")# Expected output: True are_brackets_balanced("[(])") # Expected output: False are_brackets_balanced("([)]") # Expected output: False are_brackets_balanced("a + b (c + d)") # Expected output: True are_brackets_balanced("{[}") # Expected output: False ``` **Notes:** * The input string can contain any characters, but only `()`, `{}`, and `[]` are significant for this check. * The function should be case-sensitive. * Ensure the implementation efficiently handles strings at the higher end of the constraint. **Hint:** You can use a stack data structure to keep track of opened brackets and ensure they are closed in the correct order.

answer:def are_brackets_balanced(s: str) -> bool: # A stack to keep track of opening brackets stack = [] # A map to keep track of the matches for each closing bracket matching_bracket = {')': '(', ']': '[', '}': '{'} # Traverse each character in the string for char in s: if char in matching_bracket.values(): # If it's an opening bracket stack.append(char) elif char in matching_bracket.keys(): # If it's a closing bracket if stack == [] or stack.pop() != matching_bracket[char]: return False return stack == [] # Return True if stack is empty, False otherwise

question:# Context You are developing a feature for a text editor application that includes a function for formatting paragraphs. The application must ensure that each line in a paragraph does not exceed a specified number of characters to maintain a neat and readable layout. # Objective Implement a function that takes a paragraph of text and a maximum line length, and formats the paragraph such that no line exceeds the maximum length. Words should not be split across lines, and space should be minimized at the end of each line. # Function Signature ```python def format_paragraph(paragraph: str, max_length: int) -> list[str]: Format a given paragraph into lines with at most max_length characters :param paragraph: A string representing the paragraph of text :param max_length: Maximum number of characters per line :return: List of strings, each representing a line of formatted text Example: >>> format_paragraph("This is a sample paragraph for testing the text formatting function.", 14) ['This is a', 'sample', 'paragraph for', 'testing the', 'text', 'formatting', 'function.'] >>> format_paragraph("Another example with a different max length.", 12) ['Another', 'example with', 'a different', 'max length.'] ``` # Constraints and Requirements 1. Assume the input `paragraph` is a non-empty string and words in the paragraph are separated by single spaces. 2. The `max_length` must be a positive integer greater than zero. 3. Each line in the returned list should contain words that fit within the given `max_length`. 4. Raise a `ValueError` if the `max_length` is less than the length of the longest word in the paragraph. # Examples - Input: `"This is a sample paragraph for testing the text formatting function."`, `14` Output: `['This is a', 'sample', 'paragraph for', 'testing the', 'text', 'formatting', 'function.']` - Input: `"Another example with a different max length."`, `12` Output: `['Another', 'example with', 'a different', 'max length.']` - Input: `"Short sentence."`, `20` Output: `['Short sentence.']` # Notes 1. The function should ensure that no words are split across lines. 2. Properly handle paragraphs where lines may end with multiple spaces if they fit within the `max_length`. 3. Test the function with various paragraphs and maximum lengths to ensure correct behavior.

answer:def format_paragraph(paragraph: str, max_length: int) -> list[str]: Format a given paragraph into lines with at most max_length characters :param paragraph: A string representing the paragraph of text :param max_length: Maximum number of characters per line :return: List of strings, each representing a line of formatted text words = paragraph.split() if any(len(word) > max_length for word in words): raise ValueError("The max_length is less than the length of the longest word.") lines = [] current_line = [] current_length = 0 for word in words: if current_length + len(word) + len(current_line) > max_length: lines.append(" ".join(current_line)) current_line = [word] current_length = len(word) else: current_line.append(word) current_length += len(word) if current_line: lines.append(" ".join(current_line)) return lines

Released under the chat License.

has loaded