Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Clean and documented. solution in Clear category for Friends by Celshade
class Friends(object):
"""Manage the names and connections amongst a network of friends.
Attributes:
connections: An iterable of sets, containing two names {'', ''}.
network (dict): A dictionary representing the connections (default={}).
Public Methods:
update(): Update 'network'.
add(): Add a connection.
remove(): Remove a connection.
names(): Return connected names.
connected(): Return all connections to a specific name.
"""
def __init__(self, connections: iter) -> None:
self.connections = list(connections)
self.network = {}
def update(self) -> None:
"""Iterate through 'connections' and update 'network'."""
for connection in self.connections:
for name in connection:
if name not in self.network:
self.network[name] = set()
alpha, beta = connection
net_alpha, net_beta = self.network[alpha], self.network[beta]
if alpha not in net_beta:
net_beta.add(alpha)
if beta not in net_alpha:
net_alpha.add(beta)
def add(self, connection: set) -> bool:
"""Return True if the connection is new, and add it, else False.
Args:
connection: A set of two names {'', ''}.
"""
if connection not in self.connections:
self.connections.append(connection)
return True
else:
return False
def remove(self, connection: set) -> bool:
"""Return True if the connection exists, and remove it, else False.
Args:
connection: A set of two names {'', ''}.
"""
if connection in self.connections:
self.connections.remove(connection)
return True
else:
return False
def names(self) -> set:
"""Return a set of names that have a connection with somebody."""
self.update()
return {key for key in self.network}
def connected(self, name: str) -> set:
"""Return a set of names connected to the given name.
Args:
name: The name to search for connections.
"""
self.update()
if name in self.network:
return self.network[name]
else:
return set()
Sept. 27, 2018
Comments: