树迭代中的一些问题,Python中树可以动态生成。

huangapple go评论100阅读模式
英文:

Some Issues in Tree Iteration in Python while the Tree Can be Dynamically Generated on the Fly

问题

I've translated the code portion you provided. Here it is:

  1. 我正在编写以下功能给定两组索引*_indices_lhs* *_indices_rhs*的根节点对于出现在左侧和右侧的索引中的每个索引它都会创建一个子节点其中
  2. 例如 ik, kn 将有一个子节点该子节点的 *_indices_lhs* *_indices_rhs* 分别为 i n例如 iknikn左右两侧的索引相同),预期的结果是您将有3个子节点 knknininikik当然3个子节点将分别有2个更多的子节点为了实现这一点我使用 while 循环迭代树我将创建根节点然后保持已创建子节点的引用队列然后只要此队列不为空我将迭代以创建可能会生成节点的更多子节点/节点当我遍历队列的所有内容并且它为空时我就知道不会再生成更多的子节点我为此目的实现的代码在这里
  3. 节点如下所示子节点在成员函数 generate_further_paths 中创建我创建了所有可能的子节点组合并将它们添加到 _children 成员变量中
  4. ```python
  5. class Node:
  6. _parent = None
  7. _depth = 0
  8. _indices_lhs = list()
  9. _indices_rhs = list()
  10. _children_contractions = list()
  11. _children = list()
  12. def __init__(self, indices_lhs: list[str], indices_rhs: list[str], depth: int = 0):
  13. self._indices_lhs = indices_lhs
  14. self._indices_rhs = indices_rhs
  15. self._depth = depth
  16. print(self)
  17. def generate_further_paths(self):
  18. if len(self._indices_lhs) == 0 or len(self._indices_rhs) == 0:
  19. return
  20. if len(self._indices_lhs) == 1 and len(self._indices_rhs) == 1 \
  21. and self._indices_lhs[0] == self._indices_rhs[0]:
  22. return
  23. print("D1: ", self._depth, ": ", self._indices_lhs, " | ", self._indices_rhs)
  24. intersected_indices = []
  25. for i in self._indices_lhs:
  26. if i in self._indices_rhs:
  27. intersected_indices.append(i)
  28. if len(intersected_indices) == 0:
  29. return
  30. print("Intersected indices: ", intersected_indices)
  31. for ii in intersected_indices:
  32. child_lhs = copy.deepcopy(self._indices_lhs)
  33. child_lhs.remove(ii)
  34. child_rhs = copy.deepcopy(self._indices_rhs)
  35. child_rhs.remove(ii)
  36. child = Node(child_lhs, child_rhs, self._depth + 1)
  37. self._children_contractions.append(ii)
  38. self._children.append(copy.deepcopy(child))
  39. def __str__(self):
  40. return f"Node constructed depth {self._depth}:" + "".join(self._indices_lhs) + " * " + \
  41. "".join(self._indices_rhs) + ", " + str(len(self._children)) + " children"
  42. def __repr__(self):
  43. return '<tree node representation>'

生成树的循环方法如下。我试图确保队列元素是对原始对象的引用:

  1. free_lhs = ["i", "k", "n"]
  2. free_rhs = ["i", "k", "n"]
  3. beginNode = Node(free_lhs, free_rhs, 0)
  4. beginNode.generate_further_paths()
  5. queue = copy.copy(beginNode._children)
  6. while len(queue) != 0:
  7. nq = list()
  8. for child in queue:
  9. child.generate_further_paths()
  10. nnq = copy.copy(child._children)
  11. nq += nnq
  12. queue = nq

我认为有些事情出错了,因为在此循环中,我不断获得更多的元素,某些节点在树中增加了它们的子节点数量。以下是示例输出:

  1. D1: 1 : ['i', 'k'] | ['i', 'k']
  2. Intersected indices: ['i', 'k']
  3. Node constructed depth 2:k * k, 4333 children
  4. Node constructed depth 2:i * i, 4334 children

但是深度为2的节点永远不会被迭代以生成树,但它们的子节点不断被推送回它们的成员变量 _children。我更多地来自C++领域,使用引用,我认为不应该发生这种情况,因此我认为这里有些东西没有被引用捕获。

由于名称绑定到真实对象,我希望这种方法不会成为问题。我迭代每个子节点,用生成的子节点列表覆盖前一个队列。我需要更深入地了解我的代码行为,因为我已经阅读了此帖子和其他一些来源,但我无法完全理解它。

  1. <details>
  2. <summary>英文:</summary>
  3. I am writing the following functionality. A root nodes is given with 2 set of indices (*_indices_lhs* and *_indices_rhs*), and fore every index that apperas in both the left hand side and right hand side it creates a children, where
  4. For example ik, kn will have one children where the *_indices_lhs* and *_indices_rhs* of the children will be respectively i and n. In the case of for example ikn, ikn (Identical indices on the left and right hand side) the expected outcome is that you would have 3 children kn, kn; in, in; ik, ik and ofc these 3 children would have each 2 more children. To implement this I iterate the tree with a while loop. I would create the root node and then keep a queue of references of created children, and I would then iterate as long as this queue is not empty to create further children/nodes that might create nodes. And when I iterate through all of the queue and when it is empty, then I can know that no more children can be generated. The code I have implemented for this purpose is here:
  5. The node looks as following, children are created in the member function generate_further_paths. I create all the possible children combinations and add them to _children member variable.
  6. ```python
  7. class Node:
  8. _parent = None
  9. _depth = 0
  10. _indices_lhs = list()
  11. _indices_rhs = list()
  12. _children_contractions = list()
  13. _children = list()
  14. def __init__(self, indices_lhs: list[str], indices_rhs: list[str], depth: int = 0):
  15. self._indices_lhs = indices_lhs
  16. self._indices_rhs = indices_rhs
  17. self._depth = depth
  18. print(self)
  19. def generate_further_paths(self):
  20. if len(self._indices_lhs) == 0 or len(self._indices_rhs) == 0:
  21. return
  22. if len(self._indices_lhs) == 1 and len(self._indices_rhs) == 1 \
  23. and self._indices_lhs[0] == self._indices_rhs[0]:
  24. return
  25. print(&quot;D1: &quot;, self._depth, &quot;: &quot;, self._indices_lhs, &quot; | &quot;, self._indices_rhs)
  26. intersected_indices = []
  27. for i in self._indices_lhs:
  28. if i in self._indices_rhs:
  29. intersected_indices.append(i)
  30. if len(intersected_indices) == 0:
  31. return
  32. print(&quot;Intersected indices: &quot;, intersected_indices)
  33. for ii in intersected_indices:
  34. child_lhs = copy.deepcopy(self._indices_lhs)
  35. child_lhs.remove(ii)
  36. child_rhs = copy.deepcopy(self._indices_rhs)
  37. child_rhs.remove(ii)
  38. child = Node(child_lhs, child_rhs, self._depth + 1)
  39. self._children_contractions.append(ii)
  40. self._children.append(copy.deepcopy(child))
  41. def __str__(self):
  42. return f&quot;Node constructed depth {self._depth}:&quot; + &quot;&quot;.join(self._indices_lhs) + &quot; * &quot; + \
  43. &quot;&quot;.join(self._indices_rhs) + &quot;, &quot; + str(len(self._children)) + &quot; children&quot;
  44. def __repr__(self):
  45. return &#39;&lt;tree node representation&gt;&#39;

And the loop-approach to generate the tree is as follows. I am trying to ensure that the queue elements are references to the originals:

  1. free_lhs = [&quot;i&quot;, &quot;k&quot;, &quot;n&quot;]
  2. free_rhs = [&quot;i&quot;, &quot;k&quot;, &quot;n&quot;]
  3. beginNode = Node(free_lhs, free_rhs, 0)
  4. beginNode.generate_further_paths()
  5. queue = copy.copy(beginNode._children)
  6. while len(queue) != 0:
  7. nq = list()
  8. for child in queue:
  9. child.generate_further_paths()
  10. nnq = copy.copy(child._children)
  11. nq += nnq
  12. queue = nq

I think there is something I understand that there is something wrong happening as in this loop I constantly get more elements, and some nodes in the tree increasing the number of their children. An example output:

  1. D1: 1 : [&#39;i&#39;, &#39;k&#39;] | [&#39;i&#39;, &#39;k&#39;]
  2. Intersected indices: [&#39;i&#39;, &#39;k&#39;]
  3. Node constructed depth 2:k * k, 4333 children
  4. Node constructed depth 2:i * i, 4334 children

But nodes constructed at depth 2 are never iterated for the generation, but their children are kept pushing back to their member variable _children. I come more from C++ area, and with references, I think this should not have happened so I think something here does not capture by reference.

Since the names are bound to the real objects, I was expecting this approach to not be a problem. I iterate every children overwrite the previous queue with the list of generated children. I need some further insight on have my code behaves, as I have read through this post. and some other sources but I cant grasp it much.

答案1

得分: 0

I want to post @slothrop's comment as answer as it solves the problem.

self._children = list() creates a class variable which is shared upon every instance of the class. Member variables need to be initialized in the __init__ method of the class.

英文:

I want to post @slothrop's comment as answer as it solves the problem.

self._children = list() creates a class variable which is shared upon every instance of the class. Member variables need to be initialized in the __init__ method of the class.

huangapple
  • 本文由 发表于 2023年6月29日 18:24:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76580162.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定