Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Friends by Sarina
from collections import defaultdict
class Friends:
def __init__(self, connections):
self.conn = defaultdict(set)
for c1, c2 in connections:
self.conn[c1].add(c2)
self.conn[c2].add(c1)
def add(self, connection):
c1, c2 = connection
if c2 in self.conn[c1]:
return False
else:
self.conn[c1].add(c2)
self.conn[c2].add(c1)
return True
def remove(self, connection):
c1, c2 = connection
if c2 in self.conn[c1]:
self.conn[c1].remove(c2)
self.conn[c2].remove(c1)
return True
else:
return False
def names(self):
return {k for k,v in self.conn.items() if v}
def connected(self, name):
return self.conn.get(name, set())
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
letter_friends = Friends(({"a", "b"}, {"b", "c"}, {"c", "a"}, {"a", "c"}))
digit_friends = Friends([{"1", "2"}, {"3", "1"}])
assert letter_friends.add({"c", "d"}) is True, "Add"
assert letter_friends.add({"c", "d"}) is False, "Add again"
assert letter_friends.remove({"c", "d"}) is True, "Remove"
assert digit_friends.remove({"c", "d"}) is False, "Remove non exists"
assert letter_friends.connected("d") == set(), "Non connected name"
assert letter_friends.connected("a") == {"b", "c"}, "Connected name"
assert letter_friends.names() == {"a", "b", "c"}, "Names"
Dec. 31, 2019