Search code examples
pythondictionaryrecursiondependenciestraversal

Traverse a dictionary to get dependencies (using recursion perhaps?)


This is the type of json files I am receiving:

{'n1': [5, 'number'],
 'n2': [6, 'number'],
 'm1': ['n1 x n2', 'n1 times n2'],
 'm2': ['X - m1', 'subtract n1 times n2'],
 'n3': [4, 'quarter'],
 'n4': [8, 'number'],
 'm3': ['n4 / n3', 'quarter of number n4'],
 'm4': ['m2 = m3', 'obtain m3']}

What I want is to get 'm4', and then traverse all the way back, such that 'm2=m3' becomes 'X - 5*6 = 8/4 I figure this might have something to do with recursion, but don't really have any experience with it. It has to be done in Python.

The json's I receive are of varying complexities and even further dependencies, but this is the template. Thanks!


Solution

  • Is this what you want?:

    table = {
        'n1': [5, 'number'],
        'n2': [6, 'number'],
        'm1': ['n1 x n2', 'n1 times n2'],
        'm2': ['X - m1', 'subtract n1 times n2'],
        'n3': [4, 'quarter'],
        'n4': [8, 'number'],
        'm3': ['n4 / n3', 'quarter of number n4'],
        'm4': ['m2 = m3', 'obtain m3']
    }
    
    string = 'm4'
    while True:
        for key, (value, description) in table.items():
            if key in string:
                string = string.replace(key, str(value))
                break
        else:
            break
    
    print(string)
    

    output:

    X - 5 x 6 = 8 / 4
    

    Note that if you have circular dependency or recursive dependency, this algorithm will never end.