写了一个Python版本的Trie,体验了一下Python的面向对象。
Python中对象赋值有一点需要注意:Python中的对象赋值跟Java是一样的,都是引用赋值;而拷贝函数copy.copy()也只是浅拷贝(即普通的整数类型、实数类型、字符串等基本类型可以拷过去,但是具有对象属性的东西都只是拷贝的引用),如果需要完全拷贝对象,需要copy.deepcopy()。
1 class node(object): 2 def __init__(self): 3 self.tag = False 4 self.next = {} 5 6 class Trie(object): 7 def __init__(self): 8 self.trie = node() 9 def add(self, word): 10 tree = self.trie 11 for c in word: 12 if c not in tree.next: 13 tree.next[c] = node() 14 tree = tree.next[c] 15 tree.tag= True 16 def judge(self, word): 17 tree = self.trie 18 for c in word: 19 if c not in tree.next: 20 return False 21 else: 22 tree = tree.next[c] 23 if tree.tag: 24 return True 25 else: 26 return False 27 28 tree = Trie() 29 for w in ['I', 'Love', 'You', 'Honey']: 30 tree.add(w) 31 print tree.judge('Honey') 32 print tree.judge('Hello')