我有一个定义如下的节点数据结构,并且不确定 find_matching_node 方法是pythonic还是有效的。我不太熟悉生成器,但认为使用它们可能会有更好的解决方案。有任何想法吗?
class HierarchyNode():
def __init__(self, nodeId):
self.nodeId = nodeId
self.children = {} # opted for dictionary to help reduce lookup time
def addOrGetChild(self, childNode):
return self.children.setdefault(childNode.nodeId,childNode)
def find_matching_node(self, node):
'''
look for the node in the immediate children of the current node.
if not found recursively look for it in the children nodes until
gone through all nodes
'''
matching_node = self.children.get(node.nodeId)
if matching_node:
return matching_node
else:
for child in self.children.itervalues():
matching_node = child.find_matching_node(node)
if matching_node:
return matching_node
return None