1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| _sentinel = object()
class Node:
def __init__(self, value): self._children = {} self._value = value
def _add_child(self, char, value, overwrite=False): child = self._children.get(char) if child is None: child = Node(value) self._children[char] = child elif overwrite: child._value = value return child
def find(self, key): state = self for char in key: state = state._children.get(char) if state is None: break return state
class Trie(Node): """简单实现的Trie"""
def __init__(self): super(Trie, self).__init__(_sentinel)
def __contains__(self, key): return self[key] is not None
def __getitem__(self, key): state = self for char in key: state = state._children.get(char) if state is None: return None return state._value
def __setitem__(self, key, value): state = self for i, char in enumerate(key, start=0): if i < len(key) - 1: state = state._add_child(char, None, False) else: state = state._add_child(char, value, True)
def __delitem__(self, key): self[key] = None
def add(self, key): self[key] = _sentinel
def pop(self, key): del self[key]
def update(self, keys): for key in keys: self[key] = _sentinel
|