开发者

How to propagate tree nodes in Python

开发者 https://www.devze.com 2023-03-31 01:18 出处:网络
I am dealing with a tree structure in a Python program. Each node in a tree has a dictionary \"sons\", whose keys hold arc information, and values

I am dealing with a tree structure in a Python program. Each node in a tree has a dictionary "sons", whose keys hold arc information, and values are the son nodes. The question is to propagate a list of nodes to all their sons. I use:

current_nodes = reduce(lambda s,x:s+x, map(lambda node:node.sons.values(),current_nodes),[])

Where current_nodes is the initial (and updated) list of nodes.

My program spends most time executing this reduce operation. Is there a faster way to implement that?

Thank you!

EDIT: Hi, Just let you know that the code: sum((node.sons.values() for node in current_nodes), []) although pythonic, is not really significantly faster -- if the list of nodes is long (>20000), the propagation slows down unproportionally, actually, very slow. I don't know why.

Then I define:

def Ext(nodes)
    l=[]
    for node in nodes:
        l.extend(node.sons.values())
    return l

Then I use: current_node = Ext(current_node). This approach is actually much faster. I guess sum() function is not as efficient as a list's extend method when handl开发者_开发知识库ing list concatenation.


from itertools import chain
list(chain.from_iterable(node.sons.values() for node in current_nodes))

Should be faster. map and reduce on lambdas are slow. I don't know how fast chain is; you could try

sum((node.sons.values() for node in current_nodes), [])

as well.

0

精彩评论

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