作者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
→ shaopin:PS: 基本上我只是想要作一個in order tree walk而已... 06/10 15:57
→ shaopin:PS2:import 的module只是一個很基本的tree我就不貼了 06/10 15:57
推 dotwsc:instanceMethod 要用 self.method(...) 呼叫喔 06/10 16:23
→ dotwsc:你寫的 BST.find_index_node() 是 classmethod 的呼叫方式 06/10 16:25
→ shaopin:Oh...it works..大感謝 06/11 00:10