Tone Tone - 4 days ago 5
Python Question

How to do these tasks?

pairs = {("Ana", "Berta"), ("Ana", "Greta"), ("Ana", "Helga"),
("Berta", "Cilka"), ("Berta", "Helga"),
("Cilka", "Dani"),
("Dani", "Ema"), ("Dani", "Greta"), ("Dani", "Helga"),
("Ema", "Fanči"), ("Ema", "Greta"), ("Ema", "Helga"),
("Fanči", "Iva"), ("Fanči", "Jana"), ("Fanči", "Klavdija"),
("Greta", "Helga")}

network = {"Ana": {"Berta", "Greta", "Helga"},
"Berta": {"Ana", "Helga", "Cilka"},
"Cilka": {"Berta", "Dani"},
"Dani": {"Cilka", "Ema", "Greta", "Helga"},
"Ema": {"Dani", "Fanči", "Greta", "Helga"},
"Fanči": {"Ema", "Iva", "Jana", "Klavdija"},
"Greta": {"Ana", "Dani", "Ema", "Helga"},
"Helga": {"Ana", "Berta", "Dani", "Ema", "Greta"},
"Iva": {"Fanči"},
"Jana": {"Fanči"},
"Klavdija": {"Fanči"}}


TASKS




  • to_map(pairs)
    gets a list of pairs (like above) and returns a dictionary with the network (like below above).

  • to_pairs(network)
    does the opposite.

  • n_friends(network, n)
    gets a network (the second presentation) and returns a set of names of persons that have exactly n friends.

  • onely(network)
    returns a set of names of people with only a single friend.

  • most_known(network)
    returns the name of the person with most friends.

  • common_friends(network, name1, name2)
    returns a set of common friends of the two persons.


Answer
pairs = {("Ana", "Berta"), ("Ana", "Greta"), ("Ana", "Helga"),
         ("Berta", "Cilka"), ("Berta", "Helga"),
         ("Cilka", "Dani"),
         ("Dani", "Ema"), ("Dani", "Greta"), ("Dani", "Helga"),
         ("Ema", "Fanči"), ("Ema", "Greta"), ("Ema", "Helga"),
         ("Fanči", "Iva"), ("Fanči", "Jana"), ("Fanči", "Klavdija"),
         ("Greta", "Helga")}

network = {"Ana": {"Berta", "Greta", "Helga"},
       "Berta": {"Ana", "Helga", "Cilka"},
       "Cilka": {"Berta", "Dani"},
       "Dani": {"Cilka", "Ema", "Greta", "Helga"},
       "Ema": {"Dani", "Fanči", "Greta", "Helga"},
       "Fanči": {"Ema", "Iva", "Jana", "Klavdija"},
       "Greta": {"Ana", "Dani", "Ema", "Helga"},
       "Helga": {"Ana", "Berta", "Dani", "Ema", "Greta"},
       "Iva": {"Fanči"},
       "Jana": {"Fanči"},
       "Klavdija": {"Fanči"}
       }

def to_map(pairs):
    network_ = dict()
    for name1, name2 in pairs:
        if name1 not in network: network_[name1] = set()
        network_[name1].add(name2)
    return network_

def to_pairs(network):
    pairs_ = set()
    for name1, names in network.items():
        for name2 in names:
            pairs_.add( (name1, name2) )
    return pairs_

def n_friends(network, n):
    names_ = set()
    for name1, names in network.items():
        if len(names) == n:
            names_.add(name1)
    return names_

lonely     = lambda network: n_friends(network, 1)
most_known = lambda network: sorted(network, key=lambda x: len(network[x]))[0]

don't know how to do the last

Comments