Guest User

Untitled

a guest
Jan 6th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. '''
  2. This is an Example Program to illustrate Insertion and Searching Concept over Trie Data Structure in Python
  3. '''
  4. class TrieNode:
  5. def __init__(self):
  6. self.children = [None]*26
  7. # isEndOfWord is True if node represent the end of the word thats a LEAF NODE
  8. self.isEndOfWord = False
  9.  
  10. class Trie:
  11. def __init__(self):
  12. self.root = self.getNode()
  13.  
  14. def getNode(self):
  15. return TrieNode()
  16.  
  17. def _charToIndex(self,ch):
  18. # use only 'a' through 'z' and lower case
  19. return ord(ch)-ord('a')
  20.  
  21. def insert(self,key):
  22. pointr = self.root
  23. length = len(key)
  24. for level in range(length):
  25. index = self._charToIndex(key[level])
  26. if not pointr.children[index]:
  27. pointr.children[index] = self.getNode()
  28. pointr = pointr.children[index]
  29. pointr.isEndOfWord = True
  30.  
  31. def search(self, key):
  32. pointr = self.root
  33. length = len(key)
  34. for level in range(length):
  35. index = self._charToIndex(key[level])
  36. if not pointr.children[index]:
  37. return False
  38. pointr = pointr.children[index]
  39.  
  40. return pointr != None and pointr.isEndOfWord
  41.  
  42. # driver function
  43. def main():
  44.  
  45. # Inputing keys using only 'a' through 'z' and lower case can be any length stirings since Structure is Dynamic
  46. keys = ["there","is","an","anaswer","in","some",
  47. "ones","mind","dhanush"]
  48. output = ["Not present in trie",
  49. "Present in tire"]
  50. # Trie object
  51. t = Trie()
  52. # Construct trie
  53. for key in keys:
  54. t.insert(key)
  55.  
  56. # Search for different key elements in the Trie
  57. print("{} ---- {}".format("the",output[t.search("the")]))
  58. print("{} ---- {}".format("these",output[t.search("these")]))
  59. print("{} ---- {}".format("mind",output[t.search("mind")]))
  60. print("{} ---- {}".format("dhanush",output[t.search("dhanush")]))
  61.  
  62. if __name__ == '__main__':
  63. main()
  64. '''
  65. Trie is a concept where in the Strings are stored in the tree Structure in which each node holds a single character.
  66. Trie is very Useful in word prediction Concept and Word Correction Methods.
  67. Trie's main concept is to store the values in the form of tree into which we insert strings as a whole input and branch them to traverse in am easy manner.
  68. -DhanushKJ
  69. '''
Add Comment
Please, Sign In to add comment