Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Friends by Rounin
class Friends:
def __init__(self, connections):
self.friends = dict()
for connection in connections:
self.add(connection)
def add(self, connection):
connection = list(connection)
for friend in connection:
if friend not in self.friends:
self.friends[friend] = set()
if connection[1] not in self.friends[connection[0]]:
self.friends[connection[0]].add(connection[1])
self.friends[connection[1]].add(connection[0])
return True
else:
return False
def remove(self, connection):
connection = list(connection)
if connection[0] in self.friends and connection[1] in self.friends and connection[1] in self.friends[connection[0]]:
self.friends[connection[0]].remove(connection[1])
self.friends[connection[1]].remove(connection[0])
return True
else:
return False
def names(self):
out = set()
for friend in self.friends:
if len(self.friends[friend]) > 0:
out.add(friend)
return out
def connected(self, name):
if name not in self.friends:
return set()
else:
return self.friends[name]
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"
Sept. 30, 2017