【发布时间】:2014-12-22 06:40:28
【问题描述】:
我正在尝试编写一些将多维列表转换为字典树的代码。
多维列表可能是这样的。
x = [[0,2,5],[1,1,3],[2,1,1]]
列表将始终表示 NxN 网格。把它想象成这样。
0 2 5
1 1 3
2 1 1
从左上角开始,您只能从一个节点向右或向下从一个节点到另一个节点来查找它的子节点。
So 0 would have children of 2 and 1
2 would have children of 5 and 1
5 would have children of ...
1 would have children of ...
1 would have children of 1 and 2
1 would have children of ...
2 would have children of ...
所以这个树应该是这样的:
0
/ \
/ \
/ \
/ \
/ \
2 1
/\ /\
/ \ / \
/ \ / \
1 5 2 1
/\ | | /\
/ \ | | / \
1 3 3 1 3 1
| | | | | |
1 1 1 1 1 1
这是节点及其子节点的可视化树的样子,它将由以下结构中的代码表示:
tree = {'value': 0, 'children': [
{'value': 2, 'children': [
{'value': 1, 'children': [
{'value': 1, 'children': [
{'value': 1, 'children': [None, None]}
]},
{'value': 3, 'children': [
{'value': 1, 'children': [None, None]}
]}
]},
{'value': 5, 'children': [
{'value': 3, 'children': [
{'value': 1, 'children': [None, None]}
]}
]}
]},
{'value': 1, 'children': [
{'value': 1, 'children': [
{'value': 3, 'children': [
{'value': 1, 'children': [None, None]}
]},
{'value': 1, 'children': [
{'value': 1, 'children': [None, None]}
]}
]},
{'value': 2, 'children': [
{'value': 1, 'children': [
{'value': 1, 'children': [None, None]}
]}
]}
]}
]}
如果有任何有效的方法可以将上述网格转变为正确方向的形状字典指导,那将非常有帮助。我试过这个:http://repl.it/6sU 没有运气,因为递归太深了,但是我想不出另一种方法来做到这一点。谢谢。
【问题讨论】:
-
为什么要将矩阵的半紧凑编码转换为这种可怕的树结构?为什么不将其存储为矩阵?你甚至可以使用 NumPy。
-
Bhttp://stackoverflow.com/questions/27595162/binary-tree-traversal-sum-of-each-depth/27595260 这是我关于采用书面结构并将其转化为总和清单。我正在尝试获取多维列表并计算从左上角到右下角的每个可能的数字总和
-
你这样做是为了求最小和最大还是什么别的原因?
-
找到最接近给定#的总和
标签: python algorithm multidimensional-array tree