(cases)
return sorted_ids
returns all cases in topological order

    Using Kahn's algorithm from here:
    https://en.wikipedia.org/wiki/Topological_sorting
    L = sorted_ids
    roots = S
    root_id = n
    case_id = m
returns all cases in topological order
returns all cases in topological order
def topological_sort_cases(cases):
    """returns all cases in topological order

    Using Kahn's algorithm from here:
    https://en.wikipedia.org/wiki/Topological_sorting
    L = sorted_ids
    roots = S
    root_id = n
    case_id = m

    """
    graph = {}
    inverse_graph = defaultdict(list)
    roots = []

    # compile graph
    for case_id, case in cases.items():
        graph[case.case_id] = indices = []
        for index in case.index.values():
            indices.append(index.case_id)
            inverse_graph[index.case_id].append(case.case_id)
        if not indices:
            roots.append(case.case_id)

    # sort graph
    sorted_ids = []
    while roots:
        root_id = roots.pop()
        sorted_ids.append(root_id)
        for case_id in sorted(inverse_graph[root_id]):
            graph[case_id].remove(root_id)
            if not graph[case_id]:
                roots.append(case_id)

    for indices in graph.values():
        if indices:
            raise ValueError("graph has cycles")

    return sorted_ids
def topological_sort_cases ( cases ) : graph = { } inverse_graph = defaultdict ( list ) roots = [ ] # compile graph for case_id , case in cases . items ( ) : graph [ case . case_id ] = indices = [ ] for index in case . index . values ( ) : indices . append ( index . case_id ) inverse_graph [ index . case_id ] . append ( case . case_id ) if not indices : roots . append ( case . case_id ) # sort graph sorted_ids = [ ] while roots : root_id = roots . pop ( ) sorted_ids . append ( root_id ) for case_id in sorted ( inverse_graph [ root_id ] ) : graph [ case_id ] . remove ( root_id ) if not graph [ case_id ] : roots . append ( case_id ) for indices in graph . values ( ) : if indices : raise ValueError ( "graph has cycles" ) return sorted_ids