【发布时间】:2020-05-03 11:09:40
【问题描述】:
我需要你的帮助,或者你能给我一些建议。我真的很挣扎,一些帮助会很完美,所以这就是我到目前为止所得到的;
import BST, TreeNode
class Bibliography:
def __init__(self):
self.bibtree = BST()
def getReference(self,key):
"""Return the reference for the key, if it exists, otherwise None."""
theValue = self.bibtree.retrieveKey(key,self.bibtree.root)
if theValue == None:
return None
else:
return theValue.payload
def addReference(self, key, value):
"""Add the reference represented by key and value.
Assume the key does not exist in the bibliography.
"""
self.bibtree.insertNode(key, value)
def removeReference(self, key):
"""Remove the reference with this key.
Assume the key exists in the bibliography.
"""
self.bibtree.deleteNode(key)
def outputBibliography(self):
"""Return a string with all references in alphabetical order.
There must be an empty line after each reference
"""
return self.traverse(self.bibtree.root)
def traverse(self, aNode):
"""Return a string with the references in the subtree rooted at aNode.
The references should be ordered alphabetically,
with an empty line after each reference
and a space between each key and its value. See the test file.
"""
if aNode:
self.traverse(aNode.leftChild)
return str(aNode.key, aNode.payload, end='\n\n')
self.traverse(aNode.right)
当我进行测试时,下面的函数不起作用并且需要帮助。它将它作为这个括号 [] 中的列表返回,我不想要这个。我也想要一个空行,这也不会发生。我不确定我做错了什么,如果您能给我一些建议,这将有所帮助。
def traverse(self, aNode):
"""Return a string with the references in the subtree rooted at aNode.
The references should be ordered alphabetically,
with an empty line after each reference
and a space between each key and its value. See the test file.
"""
res = []
if aNode:
res = self.traverse(aNode.leftChild)
res.append(aNode.key + ' ' + aNode.payload + '\n\n')
res = res + self.traverse(aNode.rightChild)
return res
使用此代码的输出是:
['Adams, A (1991) Loves football\n\n', 'Marlow, C (1996) Loves cricket\n\n', 'Smith, I (1994) Does not play sports\n\n']
我想要这个输出:
Adams, A (1991) Loves football
Marlow, C (1996) Loves cricket
Smith, I (1994) Does not play sports
【问题讨论】:
-
无法理解您要实现的目标,您只指定代码中发生的事情并且您不想要这种特定类型的输出,您所说的“您不想要”是什么意思想要这个”——那你想要什么?那么这篇文章的问题是什么?请提供示例代码和所需的解决方案。
-
作业的“按字母顺序遍历二叉搜索树”部分希望您进行按顺序遍历 (en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR))。你似乎已经解决了那部分。现在只是以作业要求的形式生成输出。
-
您好,谢谢您的回复,您知道我该怎么做,所以 outputBibliography(self): 可以调用吗?
-
好吧,您将返回字符串,而不是打印它。所以是这样的:
def outputBibliography(self): return '\n\n'.join(self.traverse(self.bibtree.root)) -
感谢您的快速回复,我无法触摸 def outputBibliography(self),只有 def traverse(self, aNode): 所以我应该添加 return '\n\n'.join(self .traverse(self.bibtree.root)) 到它呢?
标签: python function binary-search-tree traversal