|
| 1 | +# Copyright (c) Feb 26, 2021 CareerMonk Publications and others. |
| 2 | +# E-Mail : info@careermonk.com |
| 3 | +# Creation Date : 2021-02-26 06:15:46 |
| 4 | +# Last modification : 2021-02-26 |
| 5 | +# by : Narasimha Karumanchi |
| 6 | +# Book Title : Data Structures And Algorithmic Thinking With Python |
| 7 | +# Warranty : This software is provided "as is" without any |
| 8 | +# warranty; without even the implied warranty of |
| 9 | +# merchantability or fitness for a particular purpose. |
| 10 | + |
| 11 | +class TrieNode: |
| 12 | + def __init__(self): |
| 13 | + self.children = dict() |
| 14 | + self.isLeaf = False |
| 15 | + |
| 16 | + def insert(self, word): |
| 17 | + current = self |
| 18 | + for char in word: |
| 19 | + if char not in current.children: |
| 20 | + current.children[char] = TrieNode() |
| 21 | + current = current.children[char] |
| 22 | + current.isLeaf = True |
| 23 | + |
| 24 | + def search(self, word): |
| 25 | + current = self |
| 26 | + for char in word: |
| 27 | + if char not in current.children: |
| 28 | + return False |
| 29 | + current = current.children[char] |
| 30 | + return current.isLeaf |
| 31 | + |
| 32 | + def wordsWithPrefix(self, prefix): |
| 33 | + current = self |
| 34 | + result = [] |
| 35 | + |
| 36 | + def printer(current, path, result): |
| 37 | + if current.isLeaf == True: |
| 38 | + result.append(path) |
| 39 | + |
| 40 | + for child in current.children: |
| 41 | + printer(current.children[child], path + child, result) |
| 42 | + |
| 43 | + for char in prefix: |
| 44 | + if char not in current.children: |
| 45 | + return result |
| 46 | + current = current.children[char] |
| 47 | + |
| 48 | + printer(current, prefix, result) |
| 49 | + return result |
| 50 | + |
| 51 | + def printWords(self): |
| 52 | + current = self |
| 53 | + result = [] |
| 54 | + def printer(current, path, result): |
| 55 | + if current.isLeaf == True: |
| 56 | + result.append(path) |
| 57 | + |
| 58 | + for child in current.children: |
| 59 | + printer(current.children[child], path + child, result) |
| 60 | + |
| 61 | + printer(current, "", result) |
| 62 | + return result |
| 63 | + |
| 64 | + |
| 65 | +words = "banana bananas bandana band apple all beast" |
| 66 | + |
| 67 | +root = TrieNode() |
| 68 | +for word in words.split(" "): |
| 69 | + root.insert(word) |
| 70 | + |
| 71 | +for word in words.split(" "): |
| 72 | + print(root.search(word)) |
| 73 | + |
| 74 | +print(root.printWords()) |
| 75 | + |
| 76 | +print(root.wordsWithPrefix("a")) |
0 commit comments