GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — algorithms/tree/trie/add_and_search.py at master · deba999/algorithms Expand file tree/ Copy pathadd_and_search.pyMore file actions 81 lines (70 loc) · 2.29 KB / Copy pathadd_and_search.pyFile metadata and controls81 lines (70 loc) · 2.29 KB 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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 """ We are asked to design an efficient data structure that allows us to add and search for words. The search can be a literal word or regular expression containing “.”, where “.” can be any letter. Example: addWord(“bad”) addWord(“dad”) addWord(“mad”) search(“pad”) -> false search(“bad”) -> true search(“.ad”) -> true search(“b..”) -> true """ import collections class TrieNode(object): def __init__(self, letter, is_terminal=False): self.children = dict() self.letter = letter self.is_terminal = is_terminal class WordDictionary(object): def __init__(self): self.root = TrieNode("") def addWord(self, word): cur = self.root for letter in word: if letter not in cur.children: cur.children[letter] = TrieNode(letter) cur = cur.children[letter] cur.is_terminal = True def search(self, word, node=None): cur = node if not cur: cur = self.root for i, letter in enumerate(word): # if dot if letter == ".": if i == len(word) - 1: # if last character for child in cur.children.itervalues(): if child.is_terminal: return True return False for child in cur.children.itervalues(): if self.search(word[i + 1:], child) == True: return True return False # if letter if letter not in cur.children: return False cur = cur.children[letter] return cur.is_terminal class WordDictionary2(object): def __init__(self): self.word_dict = collections.defaultdict(list) def addWord(self, word): if word: self.word_dict[len(word)].append(word) def search(self, word): if not word: return False if '.' not in word: return word in self.word_dict[len(word)] for v in self.word_dict[len(word)]: # match xx.xx.x with yyyyyyy for i, ch in enumerate(word): if ch != v[i] and ch != '.': break else: return True return False |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |