考虑此mcve:
import sys
dct = {
-1: [0, 60000],
0: [100, 20],
100: [30],
30: [400, 500],
60000: [70, 80]
}
def ptree(parent, tree, indent=''):
print(parent)
if parent not in tree:
return
for child in tree[parent][:-1]:
print(indent + '|' + '-' * 4, end='')
ptree(child, tree, indent + '|' + ' ' * 4)
child = tree[parent][-1]
print(indent + '`' + '-' * 4, end='')
ptree(child, tree, indent + ' ' * 4)
ptree(-1, dct)
此小代码有两个问题:
为了解决第一个要点,我考虑过在代码中引入这些丑陋的条件/黑客:
def ptree(parent, tree, indent=''):
if parent != -1:
print(parent)
if parent not in tree:
return
for child in tree[parent][:-1]:
if parent != -1:
print(indent + '|' + '-' * 4, end='')
ptree(child, tree, indent + '|' + ' ' * 4)
else:
ptree(child, tree, indent)
child = tree[parent][-1]
if parent != -1:
print(indent + '`' + '-' * 4, end='')
ptree(child, tree, indent + ' ' * 4)
else:
ptree(child, tree, indent)
对于第二个要点,我不太清楚如何实现它,但是msdos tree命令显示的输出非常好,我希望我的命令以完全相同的方式显示树,这是一个示例如下所示:
问题:您如何调整上面的代码,以便正确解决上述2个要点?
答案 0 :(得分:2)
通过反复试验,我以某种方式最终得到了一种似乎吐出原始树所产生的结果的解决方案:
def ptree(start, tree, indent_width=4):
def _ptree(start, parent, tree, grandpa=None, indent=""):
if parent != start:
if grandpa is None: # Ask grandpa kids!
print(parent, end="")
else:
print(parent)
if parent not in tree:
return
for child in tree[parent][:-1]:
print(indent + "├" + "─" * indent_width, end="")
_ptree(start, child, tree, parent, indent + "│" + " " * 4)
child = tree[parent][-1]
print(indent + "└" + "─" * indent_width, end="")
_ptree(start, child, tree, parent, indent + " " * 5) # 4 -> 5
parent = start
_ptree(start, parent, tree)
dct = {
-1: [0, 60000],
0: [100, 20, 10],
100: [30],
30: [400, 500],
60000: [70, 80, 600],
500: [495, 496, 497]
}
除了使用正确的连接器之外,检查祖父并将上次ptree调用的缩进从4增加到5是关键。
ptree(-1, dct)
# Out
├────0
│ ├────100
│ │ └────30
│ │ ├────400
│ │ └────500
│ │ ├────495
│ │ ├────496
│ │ └────497
│ ├────20
│ └────10
└────60000
├────70
├────80
└────600
答案 1 :(得分:1)
第一个问题很简单:检查父值;如果是-1,则不要打印。
缩进量是根据节点值的打印图像移动的问题,而不是恒定的4个空格。 math
程序包具有完成任务的log10
和ceil
方法。
import sys
import math
dct = {
-1: [0, 60000],
0: [100, 20, 7],
100: [30],
30: [400, 500],
60000: [70, 80],
7: [9, 11, 13],
}
def ptree(parent, tree, indent=''):
if parent != -1:
print(parent)
if parent not in tree:
return
shift = math.ceil(math.log10(parent)) \
if parent >= 10 else 1
indent += ' ' * shift
for child in tree[parent][:-1]:
print(indent + '|' + '-' * 4, end='')
ptree(child, tree, indent + '|' + ' ' * 4)
child = tree[parent][-1]
print(indent + '`' + '-' * 4, end='')
ptree(child, tree, indent + ' ' * 4)
ptree(-1, dct)
输出:
|----0
| |----100
| | `----30
| | |----400
| | `----500
| |----20
| `----7
| |----9
| |----11
| `----13
`----60000
|----70
`----80