字典树 python实现

# -*- encoding:utf8 -*-
class Trie(object):

	def __init__(self):
		self.root = dict()

	def findnode(self, string):
		current_dict = self.root
		temp = None
		idx = 0
		while idx < len(string):
			temp = string[idx]
			if temp in current_dict.keys():
				current_dict = current_dict[temp]
				idx = idx + 1
			else:
				break
		return idx, current_dict

	def insert(self, string):
		idx, current_dict = self.findnode(string)
		length = len(string)
		if idx == length:
			return
		else:
			while idx < length:
				current_dict[string[idx]] = dict()
				current_dict = current_dict[string[idx]]
				idx = idx + 1

	def search(self, string):
		"""
		如果一个单词是另一个单词的一部分,比如in和inn,如果inn被添加,而in并没有被添加,在查找
		in时也能被查到
		"""
		idx, current_dict = self.findnode(string)
		length = len(string)
		if idx == length:
			return True
		else:
			return False

	def _printvalue(self, node, lists, string):
		items = sorted(node.items(), key = lambda x:x[0])
		for item in items:
			if not item[1]:
				string.append(item[0])
				lists.append(''.join(string))
				string.pop()
			else:
				string.append(item[0])
				self._printvalue(item[1], lists, string)
				string.pop()

	def show(self, node):
		"""
		以字典序的顺序输出所有的词条
		"""
		lists = []
		string = []
		self._printvalue(node, lists, string)
		return '\n'.join(lists)

 	def delete(self, string):
 		"""
 		删除词条,尽量不影响其他的词条
 		"""
		idx, current_dict = self.findnode(string)
		length = len(string)
		if idx == length and current_dict:
			# 考虑到删除的词条可能是另一词条的一部分,为了不影响另一个词条,这个词条不会被删除
			return
		elif idx == length and not current_dict:
			i = 0
			idx = idx - 1
			dicts = self.root
			while i < idx:
				dicts = dicts[string[i]]
				i = i + 1
			dicts.pop(string[idx])
		else:
			raise Exception("%s is not exist" % string)

	def __str__(self):
		return self.show(self.root)

if __name__ == '__main__':
	t = Trie()
	t.insert('to')
	t.insert('tea')
	t.insert('ted')
	t.insert('ten')
	t.insert('a')
	t.insert('in')
	t.insert('inn')
	print t
	print t.root
	print t.search('in')
	print t.search('ted')
	print t.search('teas')
	print '======'
	t.delete('inn')
	t.delete('tea')
	t.delete('to')
	t.insert('to')
	print t

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值