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 handling list concatenation.
Should be faster.
mapandreduceonlambdas are slow. I don’t know how fastchainis; you could tryas well.