开发者

Recursive algorithm for generating a graph

开发者 https://www.devze.com 2023-02-13 15:37 出处:网络
I have some database objects that are fully linked to each other as dependencies. What i want to do is to write an algorithm to retrieve that information and represent all this as a graph. Right now a

I have some database objects that are fully linked to each other as dependencies. What i want to do is to write an algorithm to retrieve that information and represent all this as a graph. Right now a pseudocode should do the trick for me , then after i should be able to write the python implementation. Th开发者_高级运维is seems like a recursive algorithm and this is where i am stuck!

 Input (Obj)
 list = obj.getDependencies():
 if list is empty:
   return obj
 else
   for items in list:
     list1 = item.getDependencies()
     if list1 is empty:
       return item
     else:
       list2 = item.getDependencies()
       ......

My mind blows up at this point!!! how can i re-write this algorithm


If I understood correctly, you want only the leaf nodes of the tree (those with no more dependencies). Is that the case? An example using an auxiliar struct to make it runnable:

class Struct:
    def __init__(self, **entries): 
        self.__dict__.update(entries)        

obj = Struct(
    name="1",
    get_dependencies=lambda: [
        Struct(name="11", get_dependencies=lambda: []), 
        Struct(name="12", get_dependencies=lambda: [
            Struct(name="121", get_dependencies=lambda: [])
        ])
    ])

def get_all_dependencies(obj):
    ds = obj.get_dependencies()
    if not ds:
        yield obj
    for o in ds:
        for o2 in get_all_dependencies(o):
            yield o2

print [x.name for x in get_all_dependencies(obj)]
# ['11', '121']

If you like the compact code that itertools makes possible, a different implementation with the exact same idea:

import itertools

def flatten(it):
    return itertools.chain.from_iterable(it)

def get_all_dependencies(obj):
    ds = obj.get_dependencies()
    return ([obj] if not ds else flatten(get_all_dependencies(o) for o in ds))

print [x.name for x in get_all_dependencies(obj)]
# ['11', '121']
0

精彩评论

暂无评论...
验证码 换一张
取 消