def _dfs(start_nodes, rules, visited):
    """
    Depth First Search
    start_nodes - Dictionary of Rule with dependencies (as Tuples):    
        start_nodes = {'A': ('B','C')}
    rules - Dictionary of Rules with dependencies (as Tuples):
    e.g.
    rules = {'A':('B','C'), 'B':('D','E'), 'C':('E','F'), 
             'D':(), 'E':(), 'F':()}
    The above rules describe the following DAG:
                    A
                   /                   B   C
                 / \\ /                 D   E   F
    usage:
    >>> rules = {'A':('B','C'), 'B':('D','E'), 'C':('E','F'), 
                 'D':(), 'E':(), 'F':()}
    >>> visited = []
    >>> list(_dfs({'A': ('B','C')}, rules, visited))
    [('A', ('B', 'C')), ('B', ('D', 'E')), ('D', ()), ('E', ()), 
    ('C', ('E', 'F')), ('F', ())]
    """
for rule, dep in list(start_nodes.items()):
    if rule not in visited:
        yield rule, dep
visited.append(rule)
for ii in dep:
    new_dep = {ii: rules[ii]}
for dep in _dfs(new_dep, rules, visited):
    if dep not in visited:
        yield dep
Алгоритм DFS в Python с генераторами