Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
defaultdict of sets solution in Clear category for Friends by Leonix
from collections import defaultdict
class Friends:
def __init__(self, connections):
# `self.friends` instance variable is a `dict`, mapping name to a `set` of friends connected to that name.
# Using `defaultdict` instead of regular `dict` helps to cut all the checks for yet non-existent names.
# Read the docs, `defaultdict` is really cool and useful.
self.friends = defaultdict(set);
for c in connections:
self.add(c)
def connected(self, name):
# This one comes for free because of how we store stuff in self.friends
return self.friends[name]
def names(self):
# This is easy too, but note that we have to check
# whether set of `connections` is empty before reporting a name
return {name for name, connections in self.friends.items() if connections}
def add(self, connection):
name1, name2 = connection
if name1 in self.friends[name2]:
# Report attempt to add the pair twice
return False
else:
# All fine, remember the connection on both ends of friendship
self.friends[name1].add(name2)
self.friends[name2].add(name1)
return True
def remove(self, connection):
try:
# Remove connection from both ends...
name1, name2 = connection
self.friends[name1].remove(name2)
self.friends[name2].remove(name1)
return True
except KeyError:
# ...unless .remove() reports there were no such connection
return False
April 4, 2019
Comments: