给定具有属性Node
的对象parent
,
class Node(object):
def __init__(self, parent=None):
self.parent = parent
我正在尝试进行以下测试:
import pytest
@pytest.fixture
def _nodes():
return {1: Node(),
2: Node(parent=5),
3: Node(),
4: Node(parent=3),
5: Node(parent=1),
6: Node(),
7: Node(parent=6),
8: Node()
}
def test_trees(_nodes):
assert trees(_nodes) == [{1, 2, 5}, {3, 4}, {6, 7}, {8}]
if __name__ == "__main__":
pytest.main([__file__])
到目前为止,我已经提出了trees
方法的以下实现:
def trees(nodes):
_trees = []
while nodes:
for u, node in nodes.items():
if node.parent is None:
_trees.append({u})
nodes.pop(u)
else:
for tree in _trees:
if node.parent in tree:
tree.add(u)
nodes.pop(u)
return _trees
但是,此实现“删除了输入”,而在我的“真实”应用程序中的相关问题中,我得到了RuntimeError
字典mutated during iteration
。
有没有更好的方法来实现trees
方法?