Task: Topological sort_Extracted top item




Go: package main

import (
    "fmt"
    "strings"
)

var data = `
FILE    FILE DEPENDENCIES
====    =================
top1    des1 ip1 ip2
top2    des1 ip2 ip3
ip1     extra1 ip1a ipcommon
ip2     ip2a ip2b ip2c ipcommon
des1    des1a des1b des1c
des1a   des1a1 des1a2
des1c   des1c1 extra1`

func main() {
    g, dep, err := parseLibDep(data)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    
    
    var tops []string
    for n := range g {
        if !dep[n] {
            tops = append(tops, n)
        }
    }
    fmt.Println("Top levels:", tops)
    
    showOrder(g, "top1")         
    showOrder(g, "top2")         
    showOrder(g, "top1", "top2") 

    fmt.Println("Cycle examples:")
    
    g, _, err = parseLibDep(data + `
des1a1  des1`)
    if err != nil {
        fmt.Println(err)
        return
    }
    showOrder(g, "top1")       
    showOrder(g, "ip1", "ip2") 
}

func showOrder(g graph, target ...string) {
    order, cyclic := g.orderFrom(target...)
    if cyclic == nil {
        reverse(order) 
        fmt.Println("Target", target, "order:", order)
    } else {
        fmt.Println("Target", target, "cyclic dependencies:", cyclic)
    }
}

func reverse(s []string) {
    last := len(s) - 1
    for i, e := range s[:len(s)/2] {
        s[i], s[last-i] = s[last-i], e
    }
}

type graph map[string][]string 
type depList map[string]bool



func parseLibDep(data string) (g graph, d depList, err error) {
    lines := strings.Split(data, "\n")
    if len(lines) < 3 || !strings.HasPrefix(lines[2], "=") {
        return nil, nil, fmt.Errorf("data format")
    }
    lines = lines[3:]
    g = graph{}
    d = depList{}
    for _, line := range lines {
        libs := strings.Fields(line)
        if len(libs) == 0 {
            continue
        }
        lib := libs[0]
        var deps []string
        for _, dep := range libs[1:] {
            g[dep] = g[dep]
            if dep == lib {
                continue
            }
            for i := 0; ; i++ {
                if i == len(deps) {
                    deps = append(deps, dep)
                    d[dep] = true
                    break
                }
                if dep == deps[i] {
                    break
                }
            }
        }
        g[lib] = deps
    }
    return g, d, nil
}






func (g graph) orderFrom(start ...string) (order, cyclic []string) {
    L := make([]string, len(g))
    i := len(L)
    temp := map[string]bool{}
    perm := map[string]bool{}
    var cycleFound bool
    var cycleStart string
    var visit func(string)
    visit = func(n string) {
        switch {
        case temp[n]:
            cycleFound = true
            cycleStart = n
            return
        case perm[n]:
            return
        }
        temp[n] = true
        for _, m := range g[n] {
            visit(m)
            if cycleFound {
                if cycleStart > "" {
                    cyclic = append(cyclic, n)
                    if n == cycleStart {
                        cycleStart = ""
                    }
                }
                return
            }
        }
        delete(temp, n)
        perm[n] = true
        i--
        L[i] = n
    }
    for _, n := range start {
        if perm[n] {
            continue
        }
        visit(n)
        if cycleFound {
            return nil, cyclic
        }
    }
    return L[i:], nil
}




Python: try:
    from functools import reduce
except: pass


def topx(data, tops=None):
    'Extract the set of top-level(s) in topological order'
    for k, v in data.items():
        v.discard(k) 
    if tops is None:
        tops = toplevels(data)
    return _topx(data, tops, [], set())

def _topx(data, tops, _sofar, _sofar_set):
    'Recursive topological extractor'
    _sofar += [tops] 
    _sofar_set.union(tops)
    depends = reduce(set.union, (data.get(top, set()) for top in tops))
    if depends:
        _topx(data, depends, _sofar, _sofar_set)
    ordered, accum = [], set()
    for s in _sofar[::-1]:
        ordered += [sorted(s - accum)]
        accum |= s
    return ordered

def printorder(order):
    'Prettyprint topological ordering'
    if order:
        print("First: " + ', '.join(str(s) for s in order[0]))
    for o in order[1:]:
        print(" Then: " + ', '.join(str(s) for s in o))

def toplevels(data):
    
    for k, v in data.items():
        v.discard(k) 
    dependents = reduce(set.union, data.values())
    return  set(data.keys()) - dependents

if __name__ == '__main__':
    data = dict(
        top1  = set('ip1 des1 ip2'.split()),
        top2  = set('ip2 des1 ip3'.split()),
        des1  = set('des1a des1b des1c'.split()),
        des1a = set('des1a1 des1a2'.split()),
        des1c = set('des1c1 extra1'.split()),
        ip2   = set('ip2a ip2b ip2c ipcommon'.split()),
        ip1   = set('ip1a ipcommon extra1'.split()),
        )

    tops = toplevels(data)
    print("The top levels of the dependency graph are: " + ' '.join(tops))

    for t in sorted(tops):
        print("\nThe compile order for top level: %s is..." % t)
        printorder(topx(data, set([t])))
    if len(tops) > 1:
        print("\nThe compile order for top levels: %s is..."
              % ' and '.join(str(s) for s in sorted(tops)) )
        printorder(topx(data, tops))