Topological sorting, recursive, using generators

Data: a list of dependencies already verified as acyclic. So here "a" depends on "b", "c" (c depends on d), etc.

A = { 'a' :  dict(b=1, c=1),
    'c' : dict(d=1),
    'd' : dict(e=1,f=1,g=1),
    'h' : dict(j=1)
    }

I would like to have a reverse solution from top to bottom, to say find a chain starting with 'a': a, c, d, e, g, f, b

So, right now (non-generational solution):

def get_all(D,k):
    L = []
    def get2(D,k):
        L.append(k)
        for ii in D.get(k,[]):
            get2(D, ii)
    get2(D,k)
    return L

Obviously, this is pretty weak :) I already banged my head on how to get profitability inside, and I would appreciate any py-foo y'all that could bring this.

+3
source share
2 answers

Try the following:

#!/usr/bin/env python

def get_all(D, k):
    yield k
    for ii in D.get(k, []):
        for jj in get_all(D, ii):
            yield jj

A = { 'a' : dict(b=1, c=1),
    'c' : dict(d=1),
    'd' : dict(e=1,f=1,g=1),
    'h' : dict(j=1)
    }

for ii in get_all(A,'a'):
    print ii

Gives me

steve @ rei : ~ / code / tmp
$ python recur.py
a
c
d
e
g
f
b
+4

, , - 'c' 'b' ( , ), : a c d e g f b d e g f

. , , :

def get_all(D, k, seen=None):
    if not seen:
        seen = set( )
    if k not in seen:
        seen.add(k)
        yield k
        for ii in D.get(k, []):
            for jj in get_all(D, ii, seen):
                yield jj
+6

Source: https://habr.com/ru/post/1697261/


All Articles