Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for City's Happiness by tokiojapan55
from functools import reduce
def subnetworks(net, crushes):
group = {(c,) for c in list(reduce(lambda a,b: a|{b[0],b[1]}, net, set()) - set(crushes))}
for n in [n for n in net if n[0] not in crushes and n[1] not in crushes]:
g0,g1 = None,None
for g in group:
if n[0] in g: g0 = g
if n[1] in g: g1 = g
if g0 != None and g1 != None and g0 != g1:
group.discard(g0)
group.discard(g1)
group.add(g0+g1)
return group
def most_crucial(net, users):
cities = list(reduce(lambda a,b: a|{b[0],b[1]}, net, set()))
happiness = dict()
for city in cities:
group = subnetworks(net, [city])
happiness[city] = sum([sum([users[gg] for gg in list(g)])**2 for g in group]) + users[city]
return [city for city in happiness.keys() if happiness[city]==min(happiness.values())]
Aug. 30, 2022