Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Third classes expirience solution in Clear category for Friends by Kolia951
import collections
class Friends:
def __init__(self, connections):
self.connections = list(connections)
def add(self, connection):
"""Add a new connection to an instance"""
if connection not in self.connections:
self.connections.append(connection)
return True
else:
return False
def remove(self, connection):
"""Remove a connection from an instance"""
if connection in self.connections:
self.connections.remove(connection)
return True
else:
return False
def names(self):
"""Print all unique names in all connections"""
all_names = set()
for pair in self.connections:
first, second = pair
all_names.add(first)
all_names.add(second)
return all_names
def connected(self, name):
"""Shows all connections of a given name"""
neighbours = collections.defaultdict(set)
for pair in self.connections:
first, second = pair
neighbours[first].add(second)
neighbours[second].add(first)
result = neighbours.get(name, set())
return result
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"
March 10, 2023