# prize35-12 Exercise 3: did the wildlife-friendly changes help? (Shannon index) import math def shannon(counts): total = sum(counts.values()) return -sum(n / total * math.log(n / total) for n in counts.values() if n) surveys = { "lawn year 0": {"blackbird": 12, "starling": 25, "house sparrow": 9, "wood pigeon": 4}, "garden year 3": {"blackbird": 10, "starling": 12, "house sparrow": 9, "wood pigeon": 4, "blue tit": 8, "robin": 6, "wren": 3}, } print("survey species birds H evenness") for name, counts in surveys.items(): h = shannon(counts) s = len(counts) print(f"{name:15} {s:8} {sum(counts.values()):6} {h:6.2f} {h / math.log(s):9.2f}") before, after = (shannon(v) for v in surveys.values()) print(f"change in H: {after - before:+.2f}") print("species gained:", sorted(set(surveys["garden year 3"]) - set(surveys["lawn year 0"]))) # Output: # survey species birds H evenness # lawn year 0 4 50 1.20 0.87 # garden year 3 7 52 1.86 0.95 # change in H: +0.66 # species gained: ['blue tit', 'robin', 'wren'] # Reading it: the index rose both because three species arrived and because the counts became more even (the starling no longer dominates). # Two surveys are only a snapshot: repeat the count in the same way, in the same season, before drawing conclusions.