Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Clear solution in Clear category for City's Happiness by cs1g
def merge(name1, name2):
return ''.join(list(set(name1) | set(name2)))
def subnetworks(net, crushes):
working_nodes = set()
for link in net:
working_nodes |= set(link)
working_nodes -= set(crushes)
working_links = []
for link in net:
if set(link) <= working_nodes:
working_links.append(link)
for link in working_links:
if len(working_nodes) == 1:
break
sub_net1 = ''
sub_net2 = ''
for sub_net in working_nodes:
if link[0] in sub_net:
sub_net1 = sub_net
if link[1] in sub_net:
sub_net2 = sub_net
if sub_net1 and sub_net2:
break
working_nodes |= set([merge(sub_net1, sub_net2)])
working_nodes -= set([sub_net1, sub_net2])
return working_nodes
def happiness(subnetworks, crush, users):
happiness = users[crush]
for sub_net in subnetworks:
sum = 0
for node in sub_net:
sum += users[node]
happiness += sum ** 2
return happiness
def most_crucial(net, users):
ratings = []
nodes = [node for node in users]
for node in nodes:
ratings.append(happiness(subnetworks(net, node), node, users))
worst = min(ratings)
crucial_nodes = []
for i in range(len(ratings)):
if ratings[i] == worst:
crucial_nodes.append(nodes[i])
return crucial_nodes
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert most_crucial([
['A', 'B'],
['B', 'C']
],{
'A': 10,
'B': 10,
'C': 10
}) == ['B'], 'First'
assert most_crucial([
['A', 'B']
],{
'A': 20,
'B': 10
}) == ['A'], 'Second'
assert most_crucial([
['A', 'B'],
['A', 'C'],
['A', 'D'],
['A', 'E']
],{
'A': 0,
'B': 10,
'C': 10,
'D': 10,
'E': 10
}) == ['A'], 'Third'
assert most_crucial([
['A', 'B'],
['B', 'C'],
['C', 'D']
],{
'A': 10,
'B': 20,
'C': 10,
'D': 20
}) == ['B'], 'Forth'
print('Nobody expected that, but you did it! It is time to share it!')
June 3, 2017