0

I am given a question as follows:

B = C, D
A = B
C = E

meaning B is dependent on variable C and D, while A is dependent on B, and so on. Variable E and D is independent.

Input of 'A' should then return:

E, C, D, B, A

listing all dependent variables. To solve this problem, I first started off by defining a dictionary to iterate this condition easily:

letter = {'A' : ['B'], 'B' : ['C', 'D'], 'C' : ['E']}

However, I am now stuck on how I should loop this in order to print all the children efficiently. I believe this is wrong but I think I may be going in the right direction:

def problem(value):
    letter = {'A' : ['B'], 'B' : ['C', 'D'], 'C' : ['E']}
    for i in letter:
        if i != value:
            continue
        if len(letter[i]) > 1:
            for k in letter:
                print("".join(letter[k]), k)
        print("".join(letter[i]), i)

Please help!

spidman
  • 13
  • 3
  • It is better to use a tree here. See http://stackoverflow.com/questions/5287516/dependencies-tree-implementation – Selcuk Feb 09 '16 at 07:11
  • Wouldn't it be better to use a directed graph? If you can use an external module, take a look at networkX. If you generate a directed graph (which is what your problem is)from your input, you can get all descendants from a node : https://networkx.github.io/documentation/latest/reference/generated/networkx.algorithms.dag.descendants.html#networkx.algorithms.dag.descendants – DainDwarf Feb 09 '16 at 07:30

2 Answers2

0

Stolen from http://code.activestate.com/recipes/576570-dependency-resolver/ after some quick googling.

def dep(arg):
    '''
        Dependency resolver

    "arg" is a dependency dictionary in which
    the values are the dependencies of their respective keys.
    '''
    d=dict((k, set(arg[k])) for k in arg)
    r=[]
    while d:
        # values not in keys (items without dep)
        t=set(i for v in d.values() for i in v)-set(d.keys())
        # and keys without value (items without dep)
        t.update(k for k, v in d.items() if not v)
        # can be done right away
        r.append(t)
        # and cleaned up
        d=dict(((k, v-t) for k, v in d.items() if v))
    return r

if __name__=='__main__':
    d=dict(
        a=('b','c'),
        b=('c','d'),
        e=(),
        f=('c','e'),
        g=('h','f'),
        i=('f',)
    )
    print dep(d)
Goodies
  • 4,439
  • 3
  • 31
  • 57
0

You have a list inside of another list. Write a nested for loop inside of another for loop and then run that through your test logic. For the outer list iterate over every part of the inner list and then move to the next part of the outer list.

Andrew Mayes
  • 95
  • 10