Appearance
question:# Scenario: You have been tasked with developing a reporting system for a financial application. One of the requirements is to generate a month-end summary report of account balances. Your goal is to create a function that, given a list of transactions, computes the final balance for each account at the end of the month. # Function Requirements: * Implement a function `calculate_balances` that processes a list of transactions and returns the final balance for each account. * Each transaction is represented as a dictionary with keys `account_id` (string), `type` (string, either "debit" or "credit"), and `amount` (float). # Constraints: * The function should handle cases where some accounts have no transactions. * Ensure the output is a dictionary where keys are account IDs and values are the final balances (floats). * Assume all balances start at 0. # Function Signature: ```python def calculate_balances(transactions: List[Dict[str, Any]]) -> Dict[str, float]: pass ``` # Example: ```python transactions = [ {"account_id": "A1", "type": "debit", "amount": 100.0}, {"account_id": "A2", "type": "credit", "amount": 200.0}, {"account_id": "A1", "type": "credit", "amount": 50.0}, {"account_id": "A3", "type": "debit", "amount": 300.0}, ] assert calculate_balances(transactions) == { "A1": -50.0, "A2": 200.0, "A3": -300.0 } ``` # Input: - `transactions` (List[Dict[str, Any]]): A list of transaction dictionaries. # Output: - (Dict[str, float]): A dictionary with account IDs as keys and final balances as values. **Good luck!**
answer:from typing import List, Dict, Any def calculate_balances(transactions: List[Dict[str, Any]]) -> Dict[str, float]: # Initialize a dictionary to keep track of balances account_balances = {} for transaction in transactions: account_id = transaction['account_id'] trans_type = transaction['type'] amount = transaction['amount'] if account_id not in account_balances: account_balances[account_id] = 0.0 if trans_type == 'debit': account_balances[account_id] -= amount elif trans_type == 'credit': account_balances[account_id] += amount else: raise ValueError(f"Unknown transaction type: {trans_type}") return account_balances
question:# Coding Assessment Question Context: In the realm of automated text processing and analysis, efficiently calculating word frequencies within large bodies of text is a crucial task. Given the capabilities of natural language processing libraries and common data structures in Python, your task is to optimize the text-processing algorithms used to determine the frequencies of words. Task: 1. Implement a function `tokenize_text(text: str) -> list[str]` that splits the input text into individual words. Remove punctuation and convert all words to lowercase. 2. Write a function `compute_word_frequencies(words: list[str]) -> dict[str, int]` that calculates the frequency of each word in the list of words. Constraints: * The text can contain a mix of uppercase and lowercase letters, punctuation, and numbers. * Your solution should focus on string processing and make use of efficient data structures such as dictionaries. * You are not allowed to use external libraries for tokenization or frequency calculation. Example Input and Output: ```python >>> text = "Hello, world! This is a test. Hello again, world." >>> tokenize_text(text) ['hello', 'world', 'this', 'is', 'a', 'test', 'hello', 'again', 'world'] >>> words = tokenize_text(text) >>> compute_word_frequencies(words) {'hello': 2, 'world': 2, 'this': 1, 'is': 1, 'a': 1, 'test': 1, 'again': 1} ``` Notes: * Ensure to handle edge cases such as an empty string or strings with only punctuation. * Optimize your code to minimize time complexity, especially during the tokenization process. * Ensure that your implementation is efficient and handles large texts gracefully.
answer:def tokenize_text(text: str) -> list[str]: Splits the input text into individual words. Removes punctuation and converts all words to lowercase. import re # Use regular expression to replace punctuation with space, then split by whitespace cleaned_text = re.sub(r'[^ws]', ' ', text) words = cleaned_text.lower().split() return words def compute_word_frequencies(words: list[str]) -> dict[str, int]: Calculates the frequency of each word in the list of words. word_frequencies = {} for word in words: if word in word_frequencies: word_frequencies[word] += 1 else: word_frequencies[word] = 1 return word_frequencies
question:# Question: Analyzing Network Traffic Flow In a given undirected graph representing a network of computers connected via cables, determine the minimum number of cables that must be added to ensure there is a direct path between any two computers (i.e., the network is fully connected). Function Signature ```python def min_cables_to_connect_network(graph: Dict[int, List[int]]) -> int: pass ``` # Input: - `graph`: A dictionary where keys represent nodes (computers) and values are lists of adjacent nodes, thus describing an undirected graph. # Output: - An integer representing the minimum number of cables needed to add to the network to make it fully connected. # Constraints: - Each node will have an integer identifier. - The graph will have at most 1000 nodes and 5000 edges. - The graph will be undirected and it can be disconnected initially. # Examples: **Example 1:** ```python graph = { 0: [1], 1: [0, 2], 2: [1], 3: [], 4: [5], 5: [4], } assert min_cables_to_connect_network(graph) == 2 ``` **Example 2:** ```python graph = { 0: [1, 2], 1: [0], 2: [0], 3: [4], 4: [3], 5: [6], 6: [5], } assert min_cables_to_connect_network(graph) == 2 ``` # Instructions: 1. Implement Depth-First Search (DFS) or Breadth-First Search (BFS) to explore the connected components of the graph. 2. Identify the number of disconnected components in the graph. 3. Calculate the minimum number of cables required to connect all the components. 4. Return the calculated number of cables. 5. Ensure your solution is efficient with respect to both time and space complexity. # Note: - Your implementation should correctly handle graphs with various degrees of connectivity, including isolated nodes. - The graph can contain cycles, so ensure your method properly considers already connected vertices to prevent redundant connections.
answer:def min_cables_to_connect_network(graph): Returns the minimum number of cables needed to make the network fully connected. def dfs(node, visited): stack = [node] while stack: current = stack.pop() for neighbor in graph[current]: if neighbor not in visited: visited.add(neighbor) stack.append(neighbor) visited = set() components = 0 for node in graph: if node not in visited: dfs(node, visited) components += 1 # To connect `components` disconnected components, we need `components - 1` cables return components - 1
question:# Question: Implementing Binary Search on a Sorted List You are required to implement a function that performs a binary search on a sorted list of integers. The function should return the index of the target element if it is present in the list and -1 if it is not found. Function Signature ```python def binary_search(sorted_list: list, target: int) -> int: pass ``` Input * `sorted_list` (list): A list of integers sorted in ascending order. The list can contain zero or more elements. * `target` (int): The integer value to search for in the list. Output * Returns the index of the `target` in the `sorted_list` if found; otherwise, it returns -1. Constraints * All elements in the `sorted_list` are integers. * The length of the `sorted_list` will not exceed 100,000. * The `target` is an integer that can be negative, zero, or positive. # Example Usage: ```python assert binary_search([], 3) == -1 assert binary_search([1], 1) == 0 assert binary_search([1, 2, 3, 4, 5], 3) == 2 assert binary_search([1, 2, 3, 4, 5], 6) == -1 assert binary_search([-5, -3, 0, 1, 2], -3) == 1 ``` # Notes 1. You must handle edge cases such as an empty list or a list with a single element. 2. Ensure that your implementation correctly handles both negative and positive integers. 3. The output index must match the zero-based indexing used in Python. # Performance Requirements * Your solution should run with a time complexity of O(log n) and a space complexity of O(1).
answer:def binary_search(sorted_list, target): left, right = 0, len(sorted_list) - 1 while left <= right: mid = (left + right) // 2 if sorted_list[mid] == target: return mid elif sorted_list[mid] < target: left = mid + 1 else: right = mid - 1 return -1