Home > Enterprise >  Recursive String Concatenation over a Dictionary
Recursive String Concatenation over a Dictionary

Time:06-10

I have a dictionary which holds the names of modules and as a value it holds a list of its submodules, each submodule is defined as ['Absolute Name', 'Relative Name'], the absoulute name is the name by which it can be found as key in my dictionary if such a module has been inserted into the dictionary.

modules_dict = {
    "ModuleB": [],
    "ModuleA": [
        [
            "ModuleB",
            "Realtive_B"
        ],
        [
            "ModuleC",
            "Relative_C"
        ],
    ],
    "ModuleC": [
        [
            "ModuleE",
            "Realtive_E"
        ],
        [
            "ModuleD",
            "Relative_D"
        ]] }

My goal is it to make "hierarchy" strings for each module/submodule where each string is that modules relative hierarchy. For this example that would be:

ModuleA.Realtive_B
ModuleA.Relative_C.Realtive_E
ModuleA.Relative_C.Relative_D
ModuleA.Relative_C

The code I have written so far achieves this in some cases but if the hierarchy gets too complex there are duplicate fragments in some strings like:

ModuleA.RelativeB.RelativeC.RelativeA.RelativeB.RelativeG

At the start of my function I am passing it the root of the hierarchy it will be working with

hierarchy_strings = []

def name_change(submodules,upper_name):
    submodules[1] =upper_name  "."   submodules[1] # submodules is a list containing absolute and relative name of a submodule ( the values of my dict )
    return submodules

def scan_submodule(module):
    try:
        for submodules in modules_dict[module[0]]:
            local_module_info = name_change(submodules,module[1])
            scan_submodule(local_module_info)
            hierarchy_strings.append(local_module_info[1])
            print(local_module_info[1])
    except KeyError:
        pass


top_module= ["ModuleA","ModuleA"]
scan_submodule(top_module)

There has to be a mistake in my way of thinking but I just cannot figure it out.

CodePudding user response:

You could use a recursive generator, like so:

def iterPaths(modules, root, path=""):
    if not path:  # Set default for path
        path = root
    yield path
    if root not in modules or not modules[root]:
        return
    for child, label in modules[root]:
        yield from iterPaths(modules, child, path   "."   label)

for path in iterPaths(modules, "ModuleA"):
    print(path)
  • Related