Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Friends by Alejandro_El_Diablo
class Friends:
def __init__(self, connections):
self.a = list(connections)
def add(self, connection):
if connection not in self.a:
self.a.append(connection)
return True
return False
def remove(self, connection):
if connection in self.a:
self.a.pop(self.a.index(connection))
return True
return False
def names(self):
from functools import reduce
return reduce(lambda x, y: x | y, self.a, set())
def connected(self, name):
from functools import reduce
def f(x, y):
z = list(y)
ret = set()
if z[0] == name:
ret.add(z[1])
if z[1] == name:
ret.add(z[0])
return x.union(ret)
return reduce(f, self.a, 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.names() == {"a", "b", "c"}, "Names"
assert letter_friends.connected("d") == set(), "Non connected name"
assert letter_friends.connected("a") == {"b", "c"}, "Connected name"
April 28, 2021
Comments: