Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
by frozenset solution in Clear category for Friends by evoynov
class Friends:
def __init__(self, connections):
self.connections = { frozenset(con) for con in connections }
def add(self, connection):
if frozenset(connection) in self.connections:
return False
self.connections.add(frozenset(connection))
return True
def remove(self, connection):
if frozenset(connection) in self.connections:
self.connections.remove(frozenset(connection))
return True
return False
def names(self):
s = set()
for con in self.connections:
s |= con
return s
def connected(self, name):
res = set()
for con in self.connections:
if name in con:
res |= con
if len(res) > 0:
res.remove(name)
return res
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.names() == {"a", "b", "c"}, "Names"
assert letter_friends.connected("d") == set(), "Non connected name"
assert letter_friends.connected("a") == {"b", "c"}, "Connected name"
Feb. 5, 2015
Comments: