Python 3D Academyবাংলা

Connecting every village with the least cable

🌍 In real life. A power company wants to bring electricity to six villages. It can lay a cable between some pairs of villages, and each possible cable has a price. A village doesn't need its own cable to every other one: power flows through the villages in between. So the company wants a set of cables that connects every village, directly or through others, for the smallest total price.

The idea in one sentence: the cheapest way to connect everything is a tree: it uses exactly V − 1 cables for V villages and never closes a loop, because a cable that closes a loop can be removed without disconnecting anyone.

Its words:

  • spanning tree: a set of edges that connects all V vertices with no loop; it always has V − 1 edges
  • minimum spanning tree (MST): a spanning tree whose total weight is as small as possible
  • loop (cycle): a way to leave a vertex and come back to it along different edges

Why V − 1 cables:

  1. start with V villages, each its own group: V groups
  2. a cable between two different groups joins them: one group fewer
  3. reaching one group takes V − 1 such cables
  4. a cable inside one group joins nothing new: it only closes a loop

Watch four villages. The first two cables join groups; the third would close a loop, so it is left out:

Why a loop is never needed. Suppose a network connects everyone and has a loop. Take out any one cable of the loop: the villages it joined are still connected the other way round the loop, so everyone is still connected, and the price dropped. So the cheapest network has no loop, and a connected network with no loop is a spanning tree.

What it costs, by counting. The simplest correct method tries every set of V − 1 cables and keeps the cheapest that connects everyone. For the six villages and their 9 possible cables that is 126 sets: fine. For 20 villages and 40 possible cables it is 131,282,408,400 sets: even at a million sets a second, a day and a half. Lessons 55.2 and 55.3 find the same answer after looking at each cable once.

from itertools import combinations

def connects_all(vertices, chosen):
    group = {v: v for v in vertices}            # each village starts as its own group
    for a, b, w in chosen:
        ga, gb = group[a], group[b]
        if ga == gb:
            return False                        # a loop: this cable joins a group to itself
        for v in vertices:
            if group[v] == gb:
                group[v] = ga                   # b's group joins a's
    return len(set(group.values())) == 1

def brute_mst(vertices, cables):
    best = None
    for chosen in combinations(cables, len(vertices) - 1):   # every set of V - 1 cables
        if connects_all(vertices, chosen):
            total = sum(w for a, b, w in chosen)
            if best is None or total < best:
                best = total
    return best

cables = [("A", "B", 4), ("A", "C", 3), ("B", "C", 2), ("B", "D", 5), ("C", "D", 6), ("C", "E", 7), ("D", "E", 1), ("D", "F", 8), ("E", "F", 9)]
print(brute_mst(["A", "B", "C", "D", "E", "F"], cables))
print(connects_all(["A", "B", "C"], [("A", "B", 1), ("B", "C", 2)]))
print(connects_all(["A", "B", "C", "D"], [("A", "B", 1), ("B", "C", 2), ("A", "C", 3)]))

Mistakes and edge cases.

  • taking the V − 1 cheapest cables: they may close a loop and leave a village out; with 1, 2, 3 on a triangle and 4 to a fourth village, the three cheapest make a loop
  • thinking the tree gives the shortest route: in the six villages the tree joins A and B through C, 3 + 2 = 5, while the cable A–B alone costs 4. An MST makes the whole network cheap, not each trip short (that is Chapter 54)
  • a graph that isn't connected: if some village can't be reached by any cable, there is no spanning tree at all
  • equal prices: there can be several minimum spanning trees, all with the same total

Quiz

  1. How many cables does a spanning tree on 10 villages use?

    • 9
    • 10
    • 45, one for every pair
  2. Why does the cheapest network never contain a loop?

    • Removing any cable of the loop keeps everyone connected and lowers the price
    • Power can't flow round a loop
    • A loop costs double
  3. What does this print?

    from itertools import combinations
    
    def connects_all(vertices, chosen):
        group = {v: v for v in vertices}            # each village starts as its own group
        for a, b, w in chosen:
            ga, gb = group[a], group[b]
            if ga == gb:
                return False                        # a loop: this cable joins a group to itself
            for v in vertices:
                if group[v] == gb:
                    group[v] = ga                   # b's group joins a's
        return len(set(group.values())) == 1
    
    def brute_mst(vertices, cables):
        best = None
        for chosen in combinations(cables, len(vertices) - 1):   # every set of V - 1 cables
            if connects_all(vertices, chosen):
                total = sum(w for a, b, w in chosen)
                if best is None or total < best:
                    best = total
        return best
    
    print(brute_mst(["A", "B", "C"], [("A", "B", 2), ("B", "C", 2), ("A", "C", 1)]))
  4. In the six villages the MST joins A and B through C (3 + 2 = 5), but the cable A–B costs 4. What does that show?

    • An MST keeps the whole network cheap, not each route short
    • The MST is wrong
    • A–B should replace B–C
  5. connects_all should say whether chosen is a spanning tree, but it says True for a set with a loop in it. After which line is a check missing?

    def connects_all(vertices, chosen):
        group = {v: v for v in vertices}
        for a, b, w in chosen:
            ga, gb = group[a], group[b]
            for v in vertices:
                if group[v] == gb:
                    group[v] = ga
        return len(set(group.values())) == 1

Coding tasks

  1. Write spanning_check(vertices, chosen): chosen is a list of cables (a, b, price). Return "has a loop" if some cable joins two villages that the earlier cables already connect, otherwise "not connected" if the cables leave more than one group, otherwise "spanning tree".

  2. Write brute_mst(vertices, cables): try every set of len(vertices) - 1 cables (use itertools.combinations) and return the smallest total of a set that connects every village, or None if no set does.