Dictionaries dependent on other dictionaries

Asked

Viewed 39 times

1

Good afternoon, I have the following problem, I have to write a function that receives a dictionary and a subject and print all the dependencies of the subject for example :

dependencias_complicado = {
    'geometria_diferencial' : [ 'análise_complexa', 'topologia' ],
    'análise_complexa' : [ 'análise_real' ],
    'análise_real' : [ 'cálculo1' ]
}

the result would be :

cálculo1
análise_real
análise_complexa
topologia

at the moment the code is like this :

def mostra_dependencias(dicionario, materia):
    for x in dicionario.get(materia):
      print(x)

what returns me only : [ 'analise_complexa', 'topologia' ]

  • Why the result would be cálculo1, 'análise_real, análise_complexa, topologia? And what entrance would this exit generate?

2 answers

3


This is a typical recursive problem - i.e., to each element to be explored, the key with the dependencies should be listed again, and for each new dependency, list the dependencies of the same.

To avoid endless cycles or even repeat dependencies that serve more than one subject, an output is to have an optional parameter in the recursive search that notes the dependencies already visited - and so, skip the ones that were already visited once:

dependencias_complicado = {
    'geometria_diferencial' : [ 'análise_complexa', 'topologia' ],
    'análise_complexa' : [ 'análise_real' ],
    'análise_real' : [ 'cálculo1' ]
}

def lineariza_dependencias(chave, dados, javistas = None):
    if javistas is None:
        javistas = set()
    resultado = [chave]
    javistas.add(chave)
    for dependencia in dados.get(chave, []):
         if dependencia not in javistas:
             resultado += lineariza_dependencias(dependencia, dados, javistas)
    return resultado

And in the Python terminal:

In [116]: lineariza_dependencias("geometria_diferencial", dependencias_complicado)                                    
Out[116]: 
['geometria_diferencial',
 'análise_complexa',
 'análise_real',
 'cálculo1',
 'topologia']

2

for x in dependencias_complicado.values():
     for y in x:
             print(y)



análise_complexa
topologia
análise_real
cálculo1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.