Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
garbage-free defaultdict-based implementation solution in Uncategorized category for Friends by pohmelie
import collections
class Friends:
def __init__(self, connections):
self.m = collections.defaultdict(set)
for con in connections:
self.add(con)
def add(self, connection):
a, b = connection
if a in self.m and b in self.m[a]:
return False
else:
self.m[a].add(b)
self.m[b].add(a)
return True
def remove_and_clear(self, a, b):
self.m[a].discard(b)
if not self.m[a]:
self.m.pop(a)
def remove(self, connection):
a, b = connection
if a not in self.m or b not in self.m[a]:
return False
else:
self.remove_and_clear(a, b)
self.remove_and_clear(b, a)
return True
def names(self):
return set(self.m)
def connected(self, name):
return self.m[name] if name in self.m else set()
Dec. 9, 2014