以下のように定義されたノード データ構造があり、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