Python 如何修改方法以打印整个字符串,而不是二叉树中的一个元素?
因此,我成功地构造了Python 如何修改方法以打印整个字符串,而不是二叉树中的一个元素?,python,python-3.x,binary-tree,binary-search-tree,Python,Python 3.x,Binary Tree,Binary Search Tree,因此,我成功地构造了string方法,以便能够打印二叉树中的元素,但问题是我希望它将整个二叉树打印为一个字符串,而不是将元素分开。我的尝试是创建一个附加元素的列表,然后只打印列表 当我尝试这种方法时,问题是当从树中获取元素时,列表只打印最新的元素,即length=1。当我尝试全局创建列表时,一切都很好,但我希望避免全局变量。我将链接整个代码,但特别是需要修复的string方法。代码与全局列表l1链接 l1 = [] class BinaryTree: def __init__(sel
string
方法,以便能够打印二叉树中的元素,但问题是我希望它将整个二叉树打印为一个字符串,而不是将元素分开。我的尝试是创建一个附加元素的列表,然后只打印列表
当我尝试这种方法时,问题是当从树中获取元素时,列表只打印最新的元素,即length=1。当我尝试全局创建列表时,一切都很好,但我希望避免全局变量。我将链接整个代码,但特别是需要修复的string
方法。代码与全局列表l1
链接
l1 = []
class BinaryTree:
def __init__(self):
"""Constructor for the binary tree."""
self._root = None
self._left = None
self._right = None
self._size = 0
self.l = []
def add(self, root):
"""Add a given element to the binary tree."""
if self._root:
if root < self._root:
if self._left is None:
self._left = BinaryTree()
self._left.add(root)
self._size += 1
elif root > self._root:
if self._right is None:
self._right = BinaryTree()
self._right.add(root)
self._size += 1
else:
self._root = root
self._size = 1
def string(self):
'''Prints the entire tree as a string.'''
#current = self._root
if self._left:
self._left.string()
#print(self._root)
l1.append(self._root)
if self._right:
self._right.string()
return l1
def len(self):
'''Returns the size of the tree (# of elements in the tree).'''
return self._size
def new():
"""Creates new instance."""
return BinaryTree()
def main():
test = new() # Test for new BT
test.add('c')
test.add('b')
test.add('a')
print(test.string())
assert test.len() == 3
if __name__ == '__main__': main()
l1=[]
类二进制树:
定义初始化(自):
“”“二叉树的构造函数。”“”
self.\u根=无
self.\u left=无
self.\u right=无
自身大小=0
self.l=[]
def添加(自我,根):
“”“将给定元素添加到二叉树。”“”
如果是self.\u root:
如果根self.\u root:
如果self.\u right为无:
self.\u right=BinaryTree()
self.\u right.add(根目录)
自身尺寸+=1
其他:
self.\u根=根
自身尺寸=1
def字符串(自):
''将整个树打印为字符串''
#电流=自根
如果self.\u离开:
self.\u left.string()
#打印(自根)
l1.追加(self.\u根)
如果你是对的:
self.\u right.string()
返回l1
def len(自我):
''返回树的大小(树中元素的大小)。''
返回自我。\u大小
def new():
“”“创建新实例。”“”
返回二进制树()
def main():
测试=新()#测试新BT
test.add('c')
test.add('b'))
test.add('a'))
打印(test.string())
断言test.len()==3
如果uuuu name_uuuuuu=='uuuuuu main:main()
您可以返回
递归调用中的节点,而不是使用全局变量来累加结果&在调用方法中累加
请参阅我定义的遍历
方法。它正在按顺序遍历树。string()
方法只是成为traverse()
返回的结果的str()
类二进制树:
定义初始化(自):
“”“二叉树的构造函数。”“”
self.\u根=无
self.\u left=无
self.\u right=无
自身大小=0
self.l=[]
def添加(自我,根):
“”“将给定元素添加到二叉树。”“”
如果是self.\u root:
如果根self.\u root:
如果self.\u right为无:
self.\u right=BinaryTree()
self.\u right.add(根目录)
自身尺寸+=1
其他:
self.\u根=根
自身尺寸=1
def遍历(自):
''将整个树打印为字符串''
要打印=[]
如果self.\u离开:
到_print.extend(self._left.traverse())
添加到打印。附加(self.\u根)
如果你是对的:
到_print.extend(self._right.traverse())
返回打印
def字符串(自):
返回str(self.traverse())
def len(自我):
''返回树的大小(树中元素的大小)。''
返回自我。\u大小
def new():
“”“创建新实例。”“”
返回二进制树()
def main():
测试=新()#测试新BT
test.add('c')
test.add('b'))
test.add('a'))
打印(test.transverse())
断言test.len()==3
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
main()
您只需对方法字符串做一点小小的更改即可使用原始代码
需要添加列表'll'作为默认参数,并在递归调用中向下传递它,如下所示
def string(self, ll = []):
'''Prints the entire tree as a string.'''
#current = self._root
if self._left:
self._left.string(ll)
#print(self._root)
ll.append(self._root)
if self._right:
self._right.string(ll)
return ll
通过将迭代合并到类中,可以简化
string
方法。如果使用这种技术,计算结构尺寸也可以利用如下所示的\uuu len\uuu
方法中所示的特征:
#! /usr/bin/env python3
def main():
test = Node()
test.add('c')
test.add('b')
test.add('a')
print(test)
assert len(test) == 3
class Node:
def __init__(self):
"""Initializes a single node to be used in a Binary Tree."""
self.__data = None
self.__left = None
self.__right = None
def add(self, data):
"""Incorporates a data value into the Binary Tree structure."""
if self.__data is None:
self.__data = data
elif data < self.__data:
if self.__left is None:
self.__left = type(self)()
self.__left.add(data)
elif data > self.__data:
if self.__right is None:
self.__right = type(self)()
self.__right.add(data)
def __str__(self):
"""Converts a Binary Tree into a string suitable for printing."""
return ''.join(map(str, self))
def __iter__(self):
"""Iterates over all values in the underlying tree structure."""
if self.__data is not None:
if self.__left is not None:
yield from self.__left
yield self.__data
if self.__right is not None:
yield from self.__right
def __len__(self):
"""Counts how many data values are stored in the underlying tree."""
return sum(1 for _ in self)
if __name__ == '__main__':
main()
确保将
update
方法添加到节点
类中。上面显示的内容不完整,但显示了需要添加的代码,以提供二叉树的额外功能。非常感谢,但是string方法中确实需要列表的str(self.traverse)函数吗?我可以直接使用遍历方法并打印列表的返回值,对吗?这是因为您希望名为string
的方法返回str
。就功能而言,它是可选的
#! /usr/bin/env python3
def main():
test = Node()
test.add('c')
test.add('b')
test.add('a')
print(test)
assert len(test) == 3
class Node:
def __init__(self):
"""Initializes a single node to be used in a Binary Tree."""
self.__data = None
self.__left = None
self.__right = None
def add(self, data):
"""Incorporates a data value into the Binary Tree structure."""
if self.__data is None:
self.__data = data
elif data < self.__data:
if self.__left is None:
self.__left = type(self)()
self.__left.add(data)
elif data > self.__data:
if self.__right is None:
self.__right = type(self)()
self.__right.add(data)
def __str__(self):
"""Converts a Binary Tree into a string suitable for printing."""
return ''.join(map(str, self))
def __iter__(self):
"""Iterates over all values in the underlying tree structure."""
if self.__data is not None:
if self.__left is not None:
yield from self.__left
yield self.__data
if self.__right is not None:
yield from self.__right
def __len__(self):
"""Counts how many data values are stored in the underlying tree."""
return sum(1 for _ in self)
if __name__ == '__main__':
main()
import sys
def main():
test = Node()
with open(sys.argv[0]) as file:
test.update(character for line in file for character in line)
print(test)
print('There are', len(test), 'unique characters in this file.')
class Node:
def update(self, iterable):
"""Takes all items from an iterable and adds them to the tree."""
for item in iterable:
self.add(item)