SlideShare a Scribd company logo
1 of 22
CREATING A
DICTIONARY
USING BST
• Since the ordinary Linked List needs to traverse on all nodes till it reaches
the object you are searching for
1
For example :
Finding the 27 in this list
3 15 18 25 27
HEAD
Starting from here==27
123456
6
We see that in Linked List it needs to traverse on
all nodes to reach the specific data [27] because
It exists at the last node.
Which means that Linked List
would traverse on (n) of nodes
for the worst case of running time.
• But in Binary Search Tree :
18
To find 27
2515
273
1
ROOT
Starting from here
==27
123
<
<
3
In Binary Search Tree it only traverse on
specific nodes that leads to the specific data [27]
by doing a comparison at each node to determine
the next node.
The Binary Search Tree
would approximately traverse on (log(n)) of nodes
for the worst case of running time.
CODE
BinarySearchTree AVLTree Node Translator
root
size
___________________
length
has_key
valueOF
bstSearch
bstMinimum
add
bstInsert
Node
Height
___________________
Search
Insert
Rebalance
Update_heights
Update_balances
Rotate_right
Rotate_left
Delete
inOreder
Display
Key
Data
Left
Right
___________________
ToString
Words
Avl
___________________
hasWord
Translate
BinarySearchTree
class BinarySearchTree:
def __init__(self):
self.root = None
self.size = 0
# Returns the number of nodes in the BST.
def length(self):
return self.size
# Determines if the BST contains the given key.
def has_key(self, key):
return self.bstSearch(self.root, key) is not None
# Returns the value associated with the key.
def ValueOf(self, key):
node = self.bstSearch(self.root, key)
# The search process starts from the root.
assert node is not None, "Invalid key." # if node=None, the function stops and message
is printed.
return node.data
BinarySearchTree
(1)
BinarySearchTree
(2)
# This method recursively searches the tree for a target key.
# This method returns the address of node or None when:
# (1) the BST is empty or (2) target doesn't exist.
def bstSearch(self, subtree, target):
if subtree is None: # base case
return None
elif target < subtree.key: # target is left of the subtree root.
return self.bstSearch(subtree.left, target)
elif target > subtree.key: # target is right of the subtree root.
return self.bstSearch(subtree.right, target)
else: # base case
return subtree
BinarySearchTree(3)
# This method returns the address of the node containing the minimum key.
def bstMinimum(self, subtree):
if subtree is None:
return None # This method returns None when the tree is empty.
else: # When the tree is not empty.
if subtree.left is None:
return subtree
else:
return self.bstMinimum(subtree.left)
# Adds a new entry to BST or replaces the value of an existing key.
def add(self, key, value):
node = self.bstSearch(self.root, key) # Find the node containing the key, if it exists.
if node is not None: # If the key is already in the tree, update its value.
node.value = value
return False
else: # Otherwise, add a new entry.
self.root = self.bstInsert(self.root, key, value) # Starting from the root.
self.size += 1
return True
# This method inserts a new item, recursively.
def bstInsert(self, subtree, key, value):
if subtree is None:
subtree = Node(key, value)
elif key < subtree.key:
subtree.left = self.bstInsert(subtree.left, key, value)
elif key > subtree.key:
subtree.right = self.bstInsert(subtree.right, key, value)
return subtree
BinarySearchTree(4)
# Removes the node associated with the given key.
def remove(self, key):
node = self.bstSearch(self.root, key) # The search process starts from the root.
assert node is not None, "Invalid key." # if node=None, the function stops and message is printed.
self.root = self.bstRemove(self.root, key) # The key exists
self.size -= 1
# This method removes an existing item recursively.
def bstRemove(self, subtree, target):
# Search for the item in the tree.
if target < subtree.key:
subtree.left = self.bstRemove(subtree.left, target)
return subtree
elif target > subtree.key:
subtree.right = self.bstRemove(subtree.right, target)
return subtree # We found the node containing the item.
else:
if subtree.left is None and subtree.right is None:
return None
elif subtree.left is None or subtree.right is None:
if subtree.left is not None:
return subtree.left
else:
return subtree.right
else:
successor = self.bstMinimum(subtree.right)
subtree.key = successor.key
subtree.value = successor.value
subtree.right = self.bstRemove(subtree.right, successor.key)
return subtree
Node
class Node:
def __init__(self, key, data):
""""Constructor"""
# The node's key
self.key = key
# The node's data
self.data = data
# The node's left child
self.left = None
# The node's right child
self.right = None
def __str__(self):
"""String representation."""
return self.ToString()
def ToString(self):
"""String representation."""
return "Key: {0}nValue: {1}".format(self.key, self.data)
Node
Translator
Translator(1)
class Translator:
"""AVLTree Implementation"""
def __init__(self):
time1 = datetime.now()
print("Loading Database...")
self.__tree = self.__getDictionary()
self.SpellChecker = self.__makeSpellChecker()
time2 = datetime.now()
print("Loaded in {0}rn".format(time2 - time1))
@staticmethod
def __getDictionary():
words = [line.rstrip('rn') for line in open("UltimateZeroDict.txt", "r", encoding='utf-8')]
avl = AVLTree()
for word in words:
temp = word.lower().split(':')
avl.insert(temp[0], temp[1])
return avl
@staticmethod
def __makeSpellChecker():
words = [line.rstrip('rn') for line in open("UltimateZeroDict.txt", "r", encoding='utf-8')]
english = []
for word in words:
temp = word.lower().split(':')
english.append(temp[0])
return SpellChecker(english)
def hasWord(self, englishWord):
return self.__tree.has_key(englishWord.lower())
Translator(2)
def Translate(self, englishWord):
englishWord = englishWord.lower()
trans = self.__tree.ValueOf(englishWord)
result = Result()
if trans is not None:
result.Value = trans
else:
result.Suggesions = self.SpellChecker.GetSuggestions(englishWord)
return result
def TranslateSentense(self, sentense):
words = sentense.split(' ')
FinalOut = ""
output = []
wrong = "Unable to recognize these words, Here are some Suggestions:rn"
w = False
for word in words:
trans = self.Translate(word)
if not trans.Translated():
wrong += word + " => " + str(trans.Suggesions) + "rn"
w = True
output.append(trans.Value if trans.Translated() else word)
FinalOut += " ".join(output) + "rn"
FinalOut += wrong if w else ""
return FinalOut
SpellChecker
SpellChecker(1)
import math
class SpellChecker:
def __init__(self, tree):
self.wordlist = tree
@staticmethod
def __areInRange(num1, num2, Range=1):
for i in range(Range + 1):
if math.fabs(num1 - num2) == i:
return True
return False
@staticmethod
def __LettersInplace(word, Input):
lettersInplace = 0
for i in range(len(Input)):
if (len(word) > i) and (word[i] == Input[i]):
lettersInplace += 1
return lettersInplace
@staticmethod
def __CommonLetters(word, Input):
commonLetters = 0
Inputs = {}
for i in range(len(Input)):
if (Inputs.get(Input[i], False)):
Inputs[Input[i]] += 1
else:
Inputs[Input[i]] = 1
for key, value in Inputs.items():
if word.count(key) == value:
commonLetters += 1
if (Input[len(Input) - 1] == word[len(word) - 1]):
commonLetters += 1
if (len(Input) == len(word)):
commonLetters += 1
if word[0] == Input[0]:
commonLetters += 1
SpellChecker(2)
@staticmethod
def __LettersInRange(word, Input):
lettersInRange = 0
for i in range(len(Input)):
if (len(word) > i) and (Input[i] in word) and SpellChecker.__areInRange(i, Input.index(word[i]) if (word[i] in Input) else -1):
lettersInRange += 1
return lettersInRange
def IsValid(self, Input):
return Input in self.__tree
def GetSuggestions(self, Input, NumOfSuggestions = 5):
arr = []
for word in self.wordlist:
if SpellChecker.__areInRange(len(word), len(Input), 1):
arr.append(word)
dic = {}
for word in arr:
NumOfSimilarities = 0
NumOfSimilarities += SpellChecker.__CommonLetters(str(word), Input)
NumOfSimilarities += SpellChecker.__LettersInplace(str(word), Input)
NumOfSimilarities += SpellChecker.__LettersInRange(str(word), Input)
dic[str(word)] = NumOfSimilarities
Maxes = []
for i in range(NumOfSuggestions):
if len(dic) > 0:
Max = list(dic.keys())[list(dic.values()).index(max(dic.values()))]
Maxes.append(Max)
del dic[str(Max)]
return Maxes
OUR TEAM

More Related Content

What's hot

What's hot (20)

php
phpphp
php
 
MySQL and its basic commands
MySQL and its basic commandsMySQL and its basic commands
MySQL and its basic commands
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Http request and http response
Http request and http responseHttp request and http response
Http request and http response
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Web forms in ASP.net
Web forms in ASP.netWeb forms in ASP.net
Web forms in ASP.net
 
Lecture 8 Enterprise Java Beans (EJB)
Lecture 8  Enterprise Java Beans (EJB)Lecture 8  Enterprise Java Beans (EJB)
Lecture 8 Enterprise Java Beans (EJB)
 
plsql les10
 plsql les10 plsql les10
plsql les10
 
AVL Tree in Data Structure
AVL Tree in Data Structure AVL Tree in Data Structure
AVL Tree in Data Structure
 
Chapter 12 ds
Chapter 12 dsChapter 12 ds
Chapter 12 ds
 
Hashing and Hash Tables
Hashing and Hash TablesHashing and Hash Tables
Hashing and Hash Tables
 
Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure Binary Heap Tree, Data Structure
Binary Heap Tree, Data Structure
 
PHP - PDO Objects
PHP - PDO ObjectsPHP - PDO Objects
PHP - PDO Objects
 
Introduction to ABAP
Introduction to ABAPIntroduction to ABAP
Introduction to ABAP
 
Inheritance in c++
Inheritance in c++ Inheritance in c++
Inheritance in c++
 
Vb decision making statements
Vb decision making statementsVb decision making statements
Vb decision making statements
 
HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and response
 
Html forms
Html formsHtml forms
Html forms
 
Fundamentals of Language Processing
Fundamentals of Language ProcessingFundamentals of Language Processing
Fundamentals of Language Processing
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive
 

Viewers also liked

Viewers also liked (11)

Doubly Linked List || Operations || Algorithms
Doubly Linked List || Operations || AlgorithmsDoubly Linked List || Operations || Algorithms
Doubly Linked List || Operations || Algorithms
 
linked list (c#)
 linked list (c#) linked list (c#)
linked list (c#)
 
Linked lists
Linked listsLinked lists
Linked lists
 
linked list
linked list linked list
linked list
 
Link List
Link ListLink List
Link List
 
Linked lists
Linked listsLinked lists
Linked lists
 
Linked list
Linked listLinked list
Linked list
 
DATA STRUCTURES
DATA STRUCTURESDATA STRUCTURES
DATA STRUCTURES
 
Dbms slides
Dbms slidesDbms slides
Dbms slides
 
SlideShare 101
SlideShare 101SlideShare 101
SlideShare 101
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
 

Similar to Python Spell Checker

Complete the implementation of the binary search tree started in cla.pdf
Complete the implementation of the binary search tree started in cla.pdfComplete the implementation of the binary search tree started in cla.pdf
Complete the implementation of the binary search tree started in cla.pdf
sanuoptical
 
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUESPYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
vanithasivdc
 
Due November 22 2021 This assignment is worth 20 of your .pdf
Due November 22 2021 This assignment is worth 20 of your .pdfDue November 22 2021 This assignment is worth 20 of your .pdf
Due November 22 2021 This assignment is worth 20 of your .pdf
abibagschennai
 

Similar to Python Spell Checker (20)

Materi Searching
Materi Searching Materi Searching
Materi Searching
 
Lecture 7-BinarySearchTrees.ppt
Lecture 7-BinarySearchTrees.pptLecture 7-BinarySearchTrees.ppt
Lecture 7-BinarySearchTrees.ppt
 
Complete the implementation of the binary search tree started in cla.pdf
Complete the implementation of the binary search tree started in cla.pdfComplete the implementation of the binary search tree started in cla.pdf
Complete the implementation of the binary search tree started in cla.pdf
 
Lecture_10 - Revised.pptx
Lecture_10 - Revised.pptxLecture_10 - Revised.pptx
Lecture_10 - Revised.pptx
 
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUESPYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
PYTHON ALGORITHMS, DATA STRUCTURE, SORTING TECHNIQUES
 
Binary search tree
Binary search treeBinary search tree
Binary search tree
 
A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced Ruby
 
08 binarysearchtrees 1
08 binarysearchtrees 108 binarysearchtrees 1
08 binarysearchtrees 1
 
L 19 ct1120
L 19 ct1120L 19 ct1120
L 19 ct1120
 
Binary search tree(bst)
Binary search tree(bst)Binary search tree(bst)
Binary search tree(bst)
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Recursion
RecursionRecursion
Recursion
 
search_sort.ppt
search_sort.pptsearch_sort.ppt
search_sort.ppt
 
Binary tree
Binary treeBinary tree
Binary tree
 
CS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdfCS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdf
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Due November 22 2021 This assignment is worth 20 of your .pdf
Due November 22 2021 This assignment is worth 20 of your .pdfDue November 22 2021 This assignment is worth 20 of your .pdf
Due November 22 2021 This assignment is worth 20 of your .pdf
 
Data Structures Design Notes.pdf
Data Structures Design Notes.pdfData Structures Design Notes.pdf
Data Structures Design Notes.pdf
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
Data Structure Searching.pptx
Data Structure Searching.pptxData Structure Searching.pptx
Data Structure Searching.pptx
 

Recently uploaded

Abortion pills in Doha {{ QATAR }} +966572737505) Get Cytotec
Abortion pills in Doha {{ QATAR }} +966572737505) Get CytotecAbortion pills in Doha {{ QATAR }} +966572737505) Get Cytotec
Abortion pills in Doha {{ QATAR }} +966572737505) Get Cytotec
Abortion pills in Riyadh +966572737505 get cytotec
 
Reconciling Conflicting Data Curation Actions: Transparency Through Argument...
Reconciling Conflicting Data Curation Actions:  Transparency Through Argument...Reconciling Conflicting Data Curation Actions:  Transparency Through Argument...
Reconciling Conflicting Data Curation Actions: Transparency Through Argument...
Bertram Ludäscher
 
sourabh vyas1222222222222222222244444444
sourabh vyas1222222222222222222244444444sourabh vyas1222222222222222222244444444
sourabh vyas1222222222222222222244444444
saurabvyas476
 
Abortion pills in Jeddah |+966572737505 | get cytotec
Abortion pills in Jeddah |+966572737505 | get cytotecAbortion pills in Jeddah |+966572737505 | get cytotec
Abortion pills in Jeddah |+966572737505 | get cytotec
Abortion pills in Riyadh +966572737505 get cytotec
 
obat aborsi Tarakan wa 081336238223 jual obat aborsi cytotec asli di Tarakan9...
obat aborsi Tarakan wa 081336238223 jual obat aborsi cytotec asli di Tarakan9...obat aborsi Tarakan wa 081336238223 jual obat aborsi cytotec asli di Tarakan9...
obat aborsi Tarakan wa 081336238223 jual obat aborsi cytotec asli di Tarakan9...
yulianti213969
 
如何办理(WashU毕业证书)圣路易斯华盛顿大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(WashU毕业证书)圣路易斯华盛顿大学毕业证成绩单本科硕士学位证留信学历认证如何办理(WashU毕业证书)圣路易斯华盛顿大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(WashU毕业证书)圣路易斯华盛顿大学毕业证成绩单本科硕士学位证留信学历认证
acoha1
 
Displacement, Velocity, Acceleration, and Second Derivatives
Displacement, Velocity, Acceleration, and Second DerivativesDisplacement, Velocity, Acceleration, and Second Derivatives
Displacement, Velocity, Acceleration, and Second Derivatives
23050636
 
Abortion pills in Riyadh Saudi Arabia| +966572737505 | Get Cytotec, Unwanted Kit
Abortion pills in Riyadh Saudi Arabia| +966572737505 | Get Cytotec, Unwanted KitAbortion pills in Riyadh Saudi Arabia| +966572737505 | Get Cytotec, Unwanted Kit
Abortion pills in Riyadh Saudi Arabia| +966572737505 | Get Cytotec, Unwanted Kit
Abortion pills in Riyadh +966572737505 get cytotec
 

Recently uploaded (20)

Abortion pills in Doha {{ QATAR }} +966572737505) Get Cytotec
Abortion pills in Doha {{ QATAR }} +966572737505) Get CytotecAbortion pills in Doha {{ QATAR }} +966572737505) Get Cytotec
Abortion pills in Doha {{ QATAR }} +966572737505) Get Cytotec
 
Reconciling Conflicting Data Curation Actions: Transparency Through Argument...
Reconciling Conflicting Data Curation Actions:  Transparency Through Argument...Reconciling Conflicting Data Curation Actions:  Transparency Through Argument...
Reconciling Conflicting Data Curation Actions: Transparency Through Argument...
 
Jual Obat Aborsi Bandung (Asli No.1) Wa 082134680322 Klinik Obat Penggugur Ka...
Jual Obat Aborsi Bandung (Asli No.1) Wa 082134680322 Klinik Obat Penggugur Ka...Jual Obat Aborsi Bandung (Asli No.1) Wa 082134680322 Klinik Obat Penggugur Ka...
Jual Obat Aborsi Bandung (Asli No.1) Wa 082134680322 Klinik Obat Penggugur Ka...
 
DAA Assignment Solution.pdf is the best1
DAA Assignment Solution.pdf is the best1DAA Assignment Solution.pdf is the best1
DAA Assignment Solution.pdf is the best1
 
sourabh vyas1222222222222222222244444444
sourabh vyas1222222222222222222244444444sourabh vyas1222222222222222222244444444
sourabh vyas1222222222222222222244444444
 
jll-asia-pacific-capital-tracker-1q24.pdf
jll-asia-pacific-capital-tracker-1q24.pdfjll-asia-pacific-capital-tracker-1q24.pdf
jll-asia-pacific-capital-tracker-1q24.pdf
 
Abortion pills in Jeddah |+966572737505 | get cytotec
Abortion pills in Jeddah |+966572737505 | get cytotecAbortion pills in Jeddah |+966572737505 | get cytotec
Abortion pills in Jeddah |+966572737505 | get cytotec
 
Case Study 4 Where the cry of rebellion happen?
Case Study 4 Where the cry of rebellion happen?Case Study 4 Where the cry of rebellion happen?
Case Study 4 Where the cry of rebellion happen?
 
Pentesting_AI and security challenges of AI
Pentesting_AI and security challenges of AIPentesting_AI and security challenges of AI
Pentesting_AI and security challenges of AI
 
obat aborsi Tarakan wa 081336238223 jual obat aborsi cytotec asli di Tarakan9...
obat aborsi Tarakan wa 081336238223 jual obat aborsi cytotec asli di Tarakan9...obat aborsi Tarakan wa 081336238223 jual obat aborsi cytotec asli di Tarakan9...
obat aborsi Tarakan wa 081336238223 jual obat aborsi cytotec asli di Tarakan9...
 
Identify Rules that Predict Patient’s Heart Disease - An Application of Decis...
Identify Rules that Predict Patient’s Heart Disease - An Application of Decis...Identify Rules that Predict Patient’s Heart Disease - An Application of Decis...
Identify Rules that Predict Patient’s Heart Disease - An Application of Decis...
 
如何办理(WashU毕业证书)圣路易斯华盛顿大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(WashU毕业证书)圣路易斯华盛顿大学毕业证成绩单本科硕士学位证留信学历认证如何办理(WashU毕业证书)圣路易斯华盛顿大学毕业证成绩单本科硕士学位证留信学历认证
如何办理(WashU毕业证书)圣路易斯华盛顿大学毕业证成绩单本科硕士学位证留信学历认证
 
Northern New England Tableau User Group (TUG) May 2024
Northern New England Tableau User Group (TUG) May 2024Northern New England Tableau User Group (TUG) May 2024
Northern New England Tableau User Group (TUG) May 2024
 
Identify Customer Segments to Create Customer Offers for Each Segment - Appli...
Identify Customer Segments to Create Customer Offers for Each Segment - Appli...Identify Customer Segments to Create Customer Offers for Each Segment - Appli...
Identify Customer Segments to Create Customer Offers for Each Segment - Appli...
 
Capstone in Interprofessional Informatic // IMPACT OF COVID 19 ON EDUCATION
Capstone in Interprofessional Informatic  // IMPACT OF COVID 19 ON EDUCATIONCapstone in Interprofessional Informatic  // IMPACT OF COVID 19 ON EDUCATION
Capstone in Interprofessional Informatic // IMPACT OF COVID 19 ON EDUCATION
 
社内勉強会資料_Object Recognition as Next Token Prediction
社内勉強会資料_Object Recognition as Next Token Prediction社内勉強会資料_Object Recognition as Next Token Prediction
社内勉強会資料_Object Recognition as Next Token Prediction
 
Credit Card Fraud Detection: Safeguarding Transactions in the Digital Age
Credit Card Fraud Detection: Safeguarding Transactions in the Digital AgeCredit Card Fraud Detection: Safeguarding Transactions in the Digital Age
Credit Card Fraud Detection: Safeguarding Transactions in the Digital Age
 
Displacement, Velocity, Acceleration, and Second Derivatives
Displacement, Velocity, Acceleration, and Second DerivativesDisplacement, Velocity, Acceleration, and Second Derivatives
Displacement, Velocity, Acceleration, and Second Derivatives
 
DBMS UNIT 5 46 CONTAINS NOTES FOR THE STUDENTS
DBMS UNIT 5 46 CONTAINS NOTES FOR THE STUDENTSDBMS UNIT 5 46 CONTAINS NOTES FOR THE STUDENTS
DBMS UNIT 5 46 CONTAINS NOTES FOR THE STUDENTS
 
Abortion pills in Riyadh Saudi Arabia| +966572737505 | Get Cytotec, Unwanted Kit
Abortion pills in Riyadh Saudi Arabia| +966572737505 | Get Cytotec, Unwanted KitAbortion pills in Riyadh Saudi Arabia| +966572737505 | Get Cytotec, Unwanted Kit
Abortion pills in Riyadh Saudi Arabia| +966572737505 | Get Cytotec, Unwanted Kit
 

Python Spell Checker

  • 1.
  • 3. • Since the ordinary Linked List needs to traverse on all nodes till it reaches the object you are searching for 1 For example : Finding the 27 in this list 3 15 18 25 27 HEAD Starting from here==27 123456
  • 4. 6 We see that in Linked List it needs to traverse on all nodes to reach the specific data [27] because It exists at the last node. Which means that Linked List would traverse on (n) of nodes for the worst case of running time.
  • 5. • But in Binary Search Tree : 18 To find 27 2515 273 1 ROOT Starting from here ==27 123 < <
  • 6. 3 In Binary Search Tree it only traverse on specific nodes that leads to the specific data [27] by doing a comparison at each node to determine the next node. The Binary Search Tree would approximately traverse on (log(n)) of nodes for the worst case of running time.
  • 8. BinarySearchTree AVLTree Node Translator root size ___________________ length has_key valueOF bstSearch bstMinimum add bstInsert Node Height ___________________ Search Insert Rebalance Update_heights Update_balances Rotate_right Rotate_left Delete inOreder Display Key Data Left Right ___________________ ToString Words Avl ___________________ hasWord Translate
  • 10. class BinarySearchTree: def __init__(self): self.root = None self.size = 0 # Returns the number of nodes in the BST. def length(self): return self.size # Determines if the BST contains the given key. def has_key(self, key): return self.bstSearch(self.root, key) is not None # Returns the value associated with the key. def ValueOf(self, key): node = self.bstSearch(self.root, key) # The search process starts from the root. assert node is not None, "Invalid key." # if node=None, the function stops and message is printed. return node.data BinarySearchTree (1)
  • 11. BinarySearchTree (2) # This method recursively searches the tree for a target key. # This method returns the address of node or None when: # (1) the BST is empty or (2) target doesn't exist. def bstSearch(self, subtree, target): if subtree is None: # base case return None elif target < subtree.key: # target is left of the subtree root. return self.bstSearch(subtree.left, target) elif target > subtree.key: # target is right of the subtree root. return self.bstSearch(subtree.right, target) else: # base case return subtree
  • 12. BinarySearchTree(3) # This method returns the address of the node containing the minimum key. def bstMinimum(self, subtree): if subtree is None: return None # This method returns None when the tree is empty. else: # When the tree is not empty. if subtree.left is None: return subtree else: return self.bstMinimum(subtree.left) # Adds a new entry to BST or replaces the value of an existing key. def add(self, key, value): node = self.bstSearch(self.root, key) # Find the node containing the key, if it exists. if node is not None: # If the key is already in the tree, update its value. node.value = value return False else: # Otherwise, add a new entry. self.root = self.bstInsert(self.root, key, value) # Starting from the root. self.size += 1 return True # This method inserts a new item, recursively. def bstInsert(self, subtree, key, value): if subtree is None: subtree = Node(key, value) elif key < subtree.key: subtree.left = self.bstInsert(subtree.left, key, value) elif key > subtree.key: subtree.right = self.bstInsert(subtree.right, key, value) return subtree
  • 13. BinarySearchTree(4) # Removes the node associated with the given key. def remove(self, key): node = self.bstSearch(self.root, key) # The search process starts from the root. assert node is not None, "Invalid key." # if node=None, the function stops and message is printed. self.root = self.bstRemove(self.root, key) # The key exists self.size -= 1 # This method removes an existing item recursively. def bstRemove(self, subtree, target): # Search for the item in the tree. if target < subtree.key: subtree.left = self.bstRemove(subtree.left, target) return subtree elif target > subtree.key: subtree.right = self.bstRemove(subtree.right, target) return subtree # We found the node containing the item. else: if subtree.left is None and subtree.right is None: return None elif subtree.left is None or subtree.right is None: if subtree.left is not None: return subtree.left else: return subtree.right else: successor = self.bstMinimum(subtree.right) subtree.key = successor.key subtree.value = successor.value subtree.right = self.bstRemove(subtree.right, successor.key) return subtree
  • 14. Node
  • 15. class Node: def __init__(self, key, data): """"Constructor""" # The node's key self.key = key # The node's data self.data = data # The node's left child self.left = None # The node's right child self.right = None def __str__(self): """String representation.""" return self.ToString() def ToString(self): """String representation.""" return "Key: {0}nValue: {1}".format(self.key, self.data) Node
  • 17. Translator(1) class Translator: """AVLTree Implementation""" def __init__(self): time1 = datetime.now() print("Loading Database...") self.__tree = self.__getDictionary() self.SpellChecker = self.__makeSpellChecker() time2 = datetime.now() print("Loaded in {0}rn".format(time2 - time1)) @staticmethod def __getDictionary(): words = [line.rstrip('rn') for line in open("UltimateZeroDict.txt", "r", encoding='utf-8')] avl = AVLTree() for word in words: temp = word.lower().split(':') avl.insert(temp[0], temp[1]) return avl @staticmethod def __makeSpellChecker(): words = [line.rstrip('rn') for line in open("UltimateZeroDict.txt", "r", encoding='utf-8')] english = [] for word in words: temp = word.lower().split(':') english.append(temp[0]) return SpellChecker(english) def hasWord(self, englishWord): return self.__tree.has_key(englishWord.lower())
  • 18. Translator(2) def Translate(self, englishWord): englishWord = englishWord.lower() trans = self.__tree.ValueOf(englishWord) result = Result() if trans is not None: result.Value = trans else: result.Suggesions = self.SpellChecker.GetSuggestions(englishWord) return result def TranslateSentense(self, sentense): words = sentense.split(' ') FinalOut = "" output = [] wrong = "Unable to recognize these words, Here are some Suggestions:rn" w = False for word in words: trans = self.Translate(word) if not trans.Translated(): wrong += word + " => " + str(trans.Suggesions) + "rn" w = True output.append(trans.Value if trans.Translated() else word) FinalOut += " ".join(output) + "rn" FinalOut += wrong if w else "" return FinalOut
  • 20. SpellChecker(1) import math class SpellChecker: def __init__(self, tree): self.wordlist = tree @staticmethod def __areInRange(num1, num2, Range=1): for i in range(Range + 1): if math.fabs(num1 - num2) == i: return True return False @staticmethod def __LettersInplace(word, Input): lettersInplace = 0 for i in range(len(Input)): if (len(word) > i) and (word[i] == Input[i]): lettersInplace += 1 return lettersInplace @staticmethod def __CommonLetters(word, Input): commonLetters = 0 Inputs = {} for i in range(len(Input)): if (Inputs.get(Input[i], False)): Inputs[Input[i]] += 1 else: Inputs[Input[i]] = 1 for key, value in Inputs.items(): if word.count(key) == value: commonLetters += 1 if (Input[len(Input) - 1] == word[len(word) - 1]): commonLetters += 1 if (len(Input) == len(word)): commonLetters += 1 if word[0] == Input[0]: commonLetters += 1
  • 21. SpellChecker(2) @staticmethod def __LettersInRange(word, Input): lettersInRange = 0 for i in range(len(Input)): if (len(word) > i) and (Input[i] in word) and SpellChecker.__areInRange(i, Input.index(word[i]) if (word[i] in Input) else -1): lettersInRange += 1 return lettersInRange def IsValid(self, Input): return Input in self.__tree def GetSuggestions(self, Input, NumOfSuggestions = 5): arr = [] for word in self.wordlist: if SpellChecker.__areInRange(len(word), len(Input), 1): arr.append(word) dic = {} for word in arr: NumOfSimilarities = 0 NumOfSimilarities += SpellChecker.__CommonLetters(str(word), Input) NumOfSimilarities += SpellChecker.__LettersInplace(str(word), Input) NumOfSimilarities += SpellChecker.__LettersInRange(str(word), Input) dic[str(word)] = NumOfSimilarities Maxes = [] for i in range(NumOfSuggestions): if len(dic) > 0: Max = list(dic.keys())[list(dic.values()).index(max(dic.values()))] Maxes.append(Max) del dic[str(Max)] return Maxes