1

我有一个数组(树),例如:

['Humidity\n', ['High', ['Outlook\n', ['Sunny', ['Temp\n', ['Hot', ['Wind\n', ['Weak', ['No']], ['Strong', ['No']]]], ['Mild', ['No']]]], ['Overcast', ['Temp\n', ['Hot', ['Yes']], ['Mild', ['Yes']]]], ['Rain', ['Temp\n', ['Mild', ['Wind\n', ['Weak', ['Yes']], ['Strong', ['No']]]]]]]], ['Normal', ['Wind\n', ['Weak', ['Outlook\n', ['Rain', ['Yes']], ['Overcast', ['Temp\n', ['Cool', ['Yes']], ['Hot', ['Yes']]]], ['Sunny', ['Yes']]]], ['Strong', ['Temp\n', ['Cool', ['No']], ['Mild', ['Outlook\n', ['Rain', ['Yes']], ['Sunny', ['Yes']]]]]]]]]

我想把它打印成一棵树。这是我的尝试

def printTree(treeToPrint, tab):
    print tab + treeToPrint[0]
    newTab = tab + "--"
    nextTree = treeToPrint[1:]
    for tree in nextTree:
        print newTab + tree[0]
        printTree(tree[1], newTab + "--")

它正在打印输出,例如:

Humidity

--High
----Outlook

------Sunny
--------Temp

----------Hot
------------Wind

--------------Weak
----------------No
--------------Strong
----------------No
----------Mild
------------No
------Overcast
--------Temp

----------Hot
------------Yes
----------Mild
------------Yes
------Rain
--------Temp

----------Mild
------------Wind

--------------Weak
----------------Yes
--------------Strong
----------------No
--Normal
----Wind

------Weak
--------Outlook

----------Rain
------------Yes
----------Overcast
------------Temp

--------------Cool
----------------Yes
--------------Hot
----------------Yes
----------Sunny
------------Yes
------Strong
--------Temp

----------Cool
------------No
----------Mild
------------Outlook

--------------Rain
----------------Yes
--------------Sunny
----------------Yes

有人可以帮我以漂亮的格式表示这棵树。

4

3 回答 3

8

有时,pprint做得很好:

>>> from pprint import pprint
>>> pprint(x)
['Humidity\n',
 ['High',
  ['Outlook\n',
   ['Sunny',
    ['Temp\n',
     ['Hot', ['Wind\n', ['Weak', ['No']], ['Strong', ['No']]]],
     ['Mild', ['No']]]],
...
于 2012-05-14T22:26:11.623 回答
6

您可以使用此处找到的代码示例:

from turtle import *
from types import *

myTree = ["A",["B",["C",["D","E"],"F"],"G","H"]];

s = 50;
startpos = (0,120)
def cntstrs(list):
  return len([item for item in list if type(item) is StringType])
def drawtree(tree, pos, head=0):
  c = cntstrs(tree)
  while len(tree):
    goto(pos)
    item = tree.pop(0)
    if head:
        write(item,1)
        drawtree(tree.pop(0),pos)
    else:
        if type(item) is StringType:
            newpos = (pos[0] + s*c/4 - s*cntstrs(tree), pos[1] - s)
            down()
            goto((newpos[0], newpos[1] + 15))
            up()
            goto(newpos)
            write(item,1)
        elif type(item) is ListType:
            drawtree(item,newpos)

up()
drawtree(myTree, startpos,1)

此代码使用 pythonTkInter包在单独的窗口中绘制树。您可以通过以下命令在 linux 中安装 TkInter:sudo apt-get install python-tk

如果你想产生这样的东西,你可以使用它:http: //upload.wikimedia.org/wikipedia/commons/thumb/f/f7/Binary_tree.svg/220px-Binary_tree.svg.png

正如您在评论中提出的那样。但这不能用于控制台中的打印..

于 2012-05-14T22:49:25.127 回答
2

这是类似的:

from collections import deque
class BTreeNode:
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

    def insertNode(self, node):
        if node.data < self.data:
            if self.left == None:
                self.left = node
            else:
                self.left.insertNode(node)
        else:
            if self.right == None:
                self.right = node
            else:
                self.right.insertNode(node)

    def printLevel(self):
        """ Breadth-first traversal, print out the data by level """
        level = 0
        lastPrintedLevel = 0
        visit = deque([])
        visit.append((self, level))
        while len(visit) != 0:
            item = visit.popleft()
            if item[1] != lastPrintedLevel:  #New line for a new level
                lastPrintedLevel +=1
                print
            print item[0].data,
            if item[0].left != None:
                visit.append((item[0].left, item[1] + 1))
            if item[0].right != None: 
                visit.append((item[0].right, item[1] + 1))


bt=BTreeNode(1,left=BTreeNode(2,left=BTreeNode(4)), 
   right=BTreeNode(3,left=BTreeNode(5),right=BTreeNode(6)))     



bt.printLevel()  

输出:

1
2 3
4 5 6

另一个替代品:

import math
from cStringIO import StringIO

def show_tree(tree, total_width=33, fill=' '):
    """Pretty-print a tree."""
    output = StringIO()
    last_row = -1
    for i, n in enumerate(tree):
        if i:
            row = int(math.floor(math.log(i+1, 2)))
        else:
            row = 0
        if row != last_row:
            output.write('\n')
        columns = 2**row
        col_width = int(math.floor((total_width * 1.0) / columns))
        output.write(str(n).center(col_width, fill))
        last_row = row
    print output.getvalue()
    print '-' * total_width
    print
    return

show_tree(range(15)) 

印刷:

                0                
       1               2        
   3       4       5       6    
 7   8   9   10  11  12  13  14 
---------------------------------  

现在只需决定数据的根是什么,然后递归地附加到 BTree 就可以了。

于 2012-05-14T23:14:47.930 回答