# prize35-3 Exercise 1: connectance and most-connected species in an invented loch web web = { "algae": [], "water plants": [], "snails": ["algae", "water plants"], "water fleas": ["algae"], "minnows": ["water fleas", "snails"], "trout": ["minnows", "snails", "water fleas"], "otter": ["trout", "minnows"], "heron": ["minnows", "trout"], } species = len(web) links = sum(len(d) for d in web.values()) print(f"{species} species, {links} links, connectance {links / (species * (species - 1)):.3f}") def degree(name): return len(web[name]) + sum(name in d for d in web.values()) ranked = sorted(web, key=degree, reverse=True) for name in ranked: print(f"{name:13s} total links {degree(name)}") print("most connected:", ranked[0]) tops = [s for s in web if not any(s in d for d in web.values())] print("top predators (eaten by nobody):", tops) # Output: # 8 species, 12 links, connectance 0.214 # minnows total links 5 # trout total links 5 # snails total links 4 # water fleas total links 3 # algae total links 2 # otter total links 2 # heron total links 2 # water plants total links 1 # most connected: minnows # top predators (eaten by nobody): ['otter', 'heron'] # Note: minnows and trout tie on 5 links; minnows is listed first because it comes first in the dictionary.