源文件 tree.py
class Node:
def __init__(self, val):
self.val = val
self.children = []
def add(self, child):
self.children.append(child)
def display(self, prefix = [], last = True):
print "".join(prefix) + "|--[%s]"%(self.val)
if self.children:
prefix.append(" " if last else "| ")
for i, n in enumerate(self.children):
n.display(prefix, not i < len(self.children) - 1)
if prefix:
prefix.pop()
class Leaf:
def __init__(self, val):
self.val = val
def display(self, prefix = [], last = True):
print "".join(prefix) + "|--" + str(self.val)
if __name__ == '__main__':
root = Node("+")
sub = Node("-")
sub.add(Leaf(2))
sub.add(Leaf(3))
root.add(Leaf(1))
root.add(sub)
root.add(Leaf(4))
root.display()
运行结果如下
|--[+]
|--1
|--[-]
| |--2
| |--3
|--4
问题 node 和 leaf 中的 display method 换一种形式或者 换一种方法表现出来 使得满足其原来结果 作业急求 高手们 拜托了
class Node:
def __init__(self, val):
self.val = val
self.children = []
def add(self, child):
self.children.append(child)
def display(self, prefix = [], last = True):
print "".join(prefix) + "|--[%s]"%(self.val)
if self.children:
prefix.append(" " if last else "| ")
for i, n in enumerate(self.children):
n.display(prefix, not i < len(self.children) - 1)
if prefix:
prefix.pop()
class Leaf:
def __init__(self, val):
self.val = val
def display(self, prefix = [], last = True):
print "".join(prefix) + "|--" + str(self.val)
if __name__ == '__main__':
root = Node("+")
sub = Node("-")
sub.add(Leaf(2))
sub.add(Leaf(3))
root.add(Leaf(1))
root.add(sub)
root.add(Leaf(4))
root.display()
运行结果如下
|--[+]
|--1
|--[-]
| |--2
| |--3
|--4
问题 node 和 leaf 中的 display method 换一种形式或者 换一种方法表现出来 使得满足其原来结果 作业急求 高手们 拜托了