Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Friends by yoichi
class Friends:
def __init__(self, connections):
self.connections = set(map(self.__encode, connections))
def __encode(self, connection):
return frozenset(connection)
def add(self, connection):
c = self.__encode(connection)
if c in self.connections:
return False
self.connections.add(c)
return True
def remove(self, connection):
c = self.__encode(connection)
if c in self.connections:
self.connections.remove(c)
return True
return False
def __merge(self, sets):
from functools import reduce
return reduce(lambda a, b: a.union(b), sets, set())
def names(self):
return self.__merge(map(set, self.connections))
def connected(self, name):
c = self.__merge(filter(lambda d: name in d, map(set, self.connections)))
if c:
c.remove(name)
return c
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"
Nov. 13, 2014