作者shaopin (Linux & Mac lover)
看板Python
标题[问题] 如何在写recursive function...?
时间Wed Jun 10 15:55:56 2009
Hi, 小弟我还在初学python的阶段
想写一个binary search tree的程式如下:
import bstsize
class BST(bstsize.BST):
"""
Adds select method to BST, starting with code from bstsize.
"""
def visit(self, node):
print "%d\n" % node.key
def find_index_node(self, node):
if (node.left != None):
BST.find_index_node(node.left)
BST.visit(node)
if (node.right != None):
BST.find_index_node(node.right)
def select(self, index):
"""
Takes a 1-based index, and returns the element at that index,
or None if the index is out-of-bounds.
"""
BST.find_index_node(self.root)
if __name__ == '__main__':
tree = BST()
tree.insert(20)
tree.insert(10)
tree.insert(30)
tree.insert(15)
tree.insert(25)
tree.insert(5)
tree.select(1)
当我执行的时候...
Traceback (most recent call last):
....(中略)
BST.find_index_node(self.root)
TypeError: unbound method find_index_node() must be called
with BST instance as first argument (got BSTnode instance instead)
我想它的意思是要我加一个instance当它的第一个argument,
可是我要怎麽加呢?
还有这样的recursive是否有什麽限制? 这样写妥当吗?
资质愚鲁,谢谢大家指教
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 99.41.79.238
1F:→ shaopin:PS: 基本上我只是想要作一个in order tree walk而已... 06/10 15:57
2F:→ shaopin:PS2:import 的module只是一个很基本的tree我就不贴了 06/10 15:57
3F:推 dotwsc:instanceMethod 要用 self.method(...) 呼叫喔 06/10 16:23
4F:→ dotwsc:你写的 BST.find_index_node() 是 classmethod 的呼叫方式 06/10 16:25
5F:→ shaopin:Oh...it works..大感谢 06/11 00:10