请求协助实现LoadBalancing类的avg_load等三个核心方法
Great question! Let's break down each of the methods you're stuck on and fix the code step by step. First, we'll define a reasonable Server class (since you didn't include it) that works seamlessly with your LoadBalancing implementation.
1. Fixing the avg_load() Method
Your original code had a critical error: you tried to add the entire self.servers list to the sum, instead of summing each server's individual load. Here's the corrected version, which uses a server's active connection count as its load:
def avg_load(self): """Calculates the average load of all servers""" total_load = 0 for server in self.servers: total_load += server.load # Sum each server's current active connections # Add a safety check to avoid division by zero (though __init__ starts with one server) return total_load / len(self.servers) if self.servers else 0
2. Implementing close_connection()
This method needs three core steps: locate the server handling the connection, instruct the server to close it, then remove the connection from the load balancer's tracking dictionary. Here's the complete implementation:
def close_connection(self, connection_id): """Closes the connection on the server corresponding to connection_id.""" # Exit early if the connection doesn't exist if connection_id not in self.connections: return # You could also raise a ValueError here for explicit error handling server = self.connections[connection_id] # Tell the server to terminate the connection server.close_connection(connection_id) # Remove the connection from our tracking system del self.connections[connection_id]
3. Building ensure_availability()
The goal here is to spin up a new server if the average load across all existing servers exceeds 50. We'll use our fixed avg_load() method to check this condition:
def ensure_availability(self): """If the average load is higher than 50, spin up a new server""" if self.avg_load() > 50: self.servers.append(Server())
Full Working Code (Including Server Class)
Here's the complete, runnable code with all fixes and the necessary Server implementation (we also added the missing server.add_connection() call in your original add_connection method):
import random class Server: def __init__(self): self.connections = [] def add_connection(self, connection_id): self.connections.append(connection_id) def close_connection(self, connection_id): if connection_id in self.connections: self.connections.remove(connection_id) @property def load(self): return len(self.connections) def __str__(self): return f"Server(load={self.load})" class LoadBalancing: def __init__(self): """Initialize the load balancing system with one server""" self.connections = {} self.servers = [Server()] def add_connection(self, connection_id): """Randomly selects a server and adds a connection to it.""" server = random.choice(self.servers) # Add the connection to the selected server server.add_connection(connection_id) # Track the connection in the load balancer self.connections[connection_id] = server def close_connection(self, connection_id): """Closes the connection on the server corresponding to connection_id.""" if connection_id not in self.connections: return server = self.connections[connection_id] server.close_connection(connection_id) del self.connections[connection_id] def avg_load(self): """Calculates the average load of all servers""" total_load = 0 for server in self.servers: total_load += server.load return total_load / len(self.servers) if self.servers else 0 def ensure_availability(self): """If the average load is higher than 50, spin up a new server""" if self.avg_load() > 50: self.servers.append(Server()) def __str__(self): """Returns a string with the load for each server.""" loads = [str(server) for server in self.servers] return "[{}]".format(",".join(loads))
Key Notes
- The
Serverclass uses a list to track active connections, with aloadproperty that returns the count of those connections. - We added edge-case handling (like checking for missing connections) to prevent runtime errors.
- The
add_connectionmethod now properly tells the selected server to track the new connection.
内容的提问来源于stack exchange,提问作者Raza Mahdi

