Exemplo n.º 1
0
class SymbolTable:
    def __init__(self):
        self.__bst = BinarySearchTree()

    def add(self, value):
        return self.__bst.insert(value)

    def __str__(self):
        return self.__bst.display()
Exemplo n.º 2
0
def index_of_words_(filename):
    index = BinarySearchTree()
    with open(filename) as inp:
        i = 0
        for line in inp:
            for word in words(line):
                i += 1
                if word in index:
                    index[word] = index[word] + [i]
                else:
                    index[word] = [i]
    return index
Exemplo n.º 3
0
 def __setitem__(self, key, data):
     """
     To set value to an item and its key into the hash table instance and can handle collisions
     :precondition: The instance of List exists and has spare space to store items
     :postcondition: The target position is assigned the input data
     :param key: Hash the key to determine which position data should be stored
     :param data: The value that need to be stored.
     :complexity: O(1) in best case, O(N) in worst case
     """
     position = self.hash(key)
     if self.array[position] is None:
         self.array[position] = BinarySearchTree()
         self.array[position].insert(key, data)
         self.count += 1
         return
     elif self.array[position].root.key == key:
         self.array[position].root.value = data
         return
     else:
         self.collision += 1
         self.array[position].insert(key, data)
         return
     # raises an IndexError if the table is already full
     raise IndexError("The hash table is full!")
Exemplo n.º 4
0
def _main():
    bottom_left_left = BSTNode(1)
    bottom_left_right = BSTNode(3)
    mid_left = BSTNode(2, left=bottom_left_left, right=bottom_left_right)


    bottom_right_right = BSTNode(6)
    mid_right = BSTNode(5, right=bottom_right_right)
    
    root = BSTNode(4, right=mid_right, left=mid_left)

    tr = BinarySearchTree(root=root, less=less_than)
    
    #print tr

    tr.insert(20)

    #print tr

    newTree = BinarySearchTree()
    newTree.insert(10)
    newTree.insert(8)
    newTree.insert(14)
    newTree.insert(13)
    newTree.insert(12)
    newTree.insert(16)
    newTree.insert(17)
    newTree.insert(18)
    newTree.insert(19)

    print newTree

    #assert newTree.root.key == 10
    #assert newTree.root.left.key == 8
    #assert newTree.root.right.key == 12
    #assert newTree.root.right.right.key == 14
    #assert newTree.root.right.left.key == 13
    #assert newTree.root.right.right.right.key == 16

    print newTree.minimum
    print newTree.root.right.minimum

    print
    print 'succ of tree.root.right.right %s' % newTree.successor(newTree.root.right.right)
    print 'succ of tree.root.left %s' % newTree.successor(newTree.root.left)
    print 'succ of tree.root %s' % newTree.successor(newTree.root)
    
    print 'pred of tree.root.right.right %s' % newTree.predecessor(newTree.root.right.right)
    print 'pred of tree.root %s' % newTree.predecessor(newTree.root)
    print 'pred of tree.root.left %s' % newTree.predecessor(newTree.root.left)

    #print 'delete tree.root.right %s' % newTree.delete_node(newTree.root.right)
    #print newTree
    #print 'delete tree.root %s' % newTree.delete_node(newTree.root)
    #print newTree.root
    #print newTree.root.right
    #print newTree

    print 'searching for a node with value 12 %s' % newTree.search(12) 

    newTree.delete_node(newTree.root)
    print newTree
Exemplo n.º 5
0
f.close()

duplicates = []  # Return the list of duplicates in this data structure

# Replace the nested for loops below with your improvements
""" for name_1 in names_1:
    for name_2 in names_2:
        if name_1 == name_2:
            duplicates.append(name_1) """
# Use a binary search tree
# BST list 1
# iterate through names on list 2 to compare them to list 1
# if the name is on both list 2 and list 1 append the name to a duplicates list

# Time complexity O(n log n)
binary_tree = BinarySearchTree('names')

for names in names_1:  # binary search tree
    binary_tree.insert(names)  # made of names from names_1 list

for name in names_2:  # find duplicates
    # if the name from names_2 list is also a name in names_1 list
    if binary_tree.contains(name):
        duplicates.append(name)  # append to duplicates list

end_time = time.time()
print(f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print(f"runtime: {end_time - start_time} seconds")

# ---------- Stretch Goal -----------
# Python has built-in tools that allow for a very efficient approach to this problem
 def __init__(self):
  self.root=None


def isSymmetric(T):
 root = T.root
 return isSpecular(root.left,root.right)

def isSpecular(l,r):
 if l == None and r == None:
  return True
 elif l != None and r != None:
  if isSpecular(l.left,r.right) and isSpecular(l.right,r.left):
   return True
  else:
   return False
 else:
  return False


T=BinarySearchTree()
T.insert(5,0)
T.insert(3,0)
T.insert(1,0)
T.insert(6,0)
T.insert(9,0)
T.insert(8,0)

print(isSymmetric(T))
Exemplo n.º 7
0
from BST import BST as BinarySearchTree
tree = BinarySearchTree()
for x in range(4):
    tree.add(x)
tree.printer()
Exemplo n.º 8
0
from BST import BinarySearchTree


def maxCoins(nums):
    n = len(nums)
    dp = [[0 for x in xrange(n)] for y in xrange(n)]

    for k in range(2, n + 1):
        for left in range(0, n - k):
            right = left + k
            for i in range(left + 1, right):
                dp[left][right] = max(
                    dp[left][right],
                    nums[left] * nums[i] * nums[right] + dp[left][i] + dp[i][right],
                )
    return dp[0][n - 1]


a = [1, 8, 5, 6, 9, 3, 0, 2, 4, 1, 7, 1]
b = [1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1]
c = [1, 5, 2, 3, 4, 1, 9, 10, 1]
print maxCoins(a)
print maxCoins(b)
print maxCoins(c)

t = BinarySearchTree()
for i in xrange(1, len(a) - 1):
    val = a[i - 1] * a[i] * a[i + 1]
    t.put(a[i], val)
Exemplo n.º 9
0
        return seg[0]

current_x = 0    
def segment_less(s1, s2):
    left1 = left_end(s1)
    right1 = right_end(s1)
    left2 = left_end(s2)
    right2 = right_end(s2)
    # I'm cheating by using division. -Jeremy
    m1 = (right1[1] - left1[1]) / (right1[0] - left1[0])
    m2 = (right2[1] - left2[1]) / (right2[0] - left2[0])
    y1 = left1[1] + m1 * (current_x - left1[0])
    y2 = left2[1] + m2 * (current_x - left2[0])
    return y1 < y2

T = BinarySearchTree(root=None, less=segment_less)

T.insert(((0 * 100, 173), (181, 370)))
T.insert(((7 * 100, 173), (181, 370)))
for n in range(1, 7):
    T.insert(((n * 100, 173), (181, 370)))
# T.insert(((291, 173), (181, 370)))
# T.insert(((432, 457), (391, 167)))
# T.insert(((297, 445), (338, 91)))
# T.insert(((169, 200), (436, 511)))
# T.insert(((168, 200), (436, 511)))
# T.insert(((168, 200), (435, 511)))

# segs = [((80, 156), (174, 427)), ((115, 154), (216, 425)), ((151, 152), (251, 415)), ((185, 149), (296, 409)), ((240, 146), (342, 395)), ((332, 145), (319, 409))]
# for s in segs:
#     T.insert(s)
start_time = time.time()

f = open('names_1.txt', 'r')
names_1 = f.read().split("\n")  # List containing 10000 names
f.close()

f = open('names_2.txt', 'r')
names_2 = f.read().split("\n")  # List containing 10000 names
f.close()
0

duplicates = []  # Return the list of duplicates in this data structure

# MVP
tree = BinarySearchTree('')

for name in names_1:
    tree.insert(name)

for name in names_2:
    if tree.contains(name):
        duplicates.append(name)

# Original
# for name_1 in names_1:
#     for name_2 in names_2:
#         if name_1 == name_2:
#             duplicates.append(name_1)

end_time = time.time()
Exemplo n.º 11
0
from BST import BinarySearchTree
'''

         3
     0       5
-1      1  4      7
'''

bst = BinarySearchTree()
bst.add_node(3)
bst.add_node(0)
bst.add_node(-1)
bst.add_node(1)
bst.add_node(5)
bst.add_node(7)
bst.add_node(4)

bst.print_inorder()
print()
'''

#don't pop every time
1. if root is none: print->pop
2. if root has left: append
3. if root is none: stack pop

print()
1. if root is none: pop and print, set root = popped right
2. else: append to stack and root = root.left

'''
Exemplo n.º 12
0
import socket
import threading
import time

from BST import BinarySearchTree
from client_handler import ClientThread

t = None
LOCALHOST = socket.gethostname()
PORT = 4000
pre_unique = 0
pre_duplicate = 0
diff_unique = 0
diff_duplicate = 0

bst = BinarySearchTree()


def run_scheduled():
    global t
    check_status()
    t = threading.Timer(10, run_scheduled)
    t.start()


def check_status():
    # this function checks the number of unique, duplicates, total unique numbers received since last run
    global pre_unique, pre_duplicate, diff_unique, diff_duplicate, bst
    diff_unique = bst.size - pre_unique
    diff_duplicate = bst.duplicates - pre_duplicate
    pre_unique = bst.size
Exemplo n.º 13
0
 def __init__(self):
     self.__bst = BinarySearchTree()
Exemplo n.º 14
0
from BST import BinarySearchTree
import time

start_time = time.time()

f = open('names_1.txt', 'r')
names_1 = f.read().split("\n")  # List containing 10000 names
f.close()

f = open('names_2.txt', 'r')
names_2 = f.read().split("\n")  # List containing 10000 names
f.close()

duplicates = []
# for name_1 in names_1:
#     for name_2 in names_2:
#         if name_1 == name_2:
#             duplicates.append(name_1)
names_tree = BinarySearchTree(names_1[0])
for name in range(1, len(names_1)):
    names_tree.insert(names_1[name])

#loop through name_2 for matching name in name_1; if present, insert to dupes
for name in names_2:
    if names_tree.contains(name):
        duplicates.append(name)

end_time = time.time()
print(f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print(f"runtime: {end_time - start_time} seconds")
Exemplo n.º 15
0
from BST import BinarySearchTree

bst = BinarySearchTree()

import random
x = list(range(20))
random.shuffle(x)
for el in x:
    bst.insert(el)
bst.root.display()

bst.remove(6)
bst.root.display()

bst.remove(10)
bst.root.display()
Exemplo n.º 16
0
from BST import BinarySearchTree


def maxCoins(nums):
    n = len(nums)
    dp = [[0 for x in xrange(n)] for y in xrange(n)]

    for k in range(2, n + 1):
        for left in range(0, n - k):
            right = left + k
            for i in range(left + 1, right):
                dp[left][right] = max(dp[left][right], nums[left] * nums[i] * nums[right] + dp[left][i] + dp[i][right])
    return dp[0][n - 1]

a = [1, 8, 5, 6, 9, 3, 0, 2, 4, 1, 7, 1]
b = [1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1]
c = [1, 5, 2, 3, 4, 1, 9, 10, 1]
print maxCoins(a)
print maxCoins(b)
print maxCoins(c)

t = BinarySearchTree()
for i in xrange(1, len(a) - 1):
    val = a[i-1]*a[i]*a[i+1]
    t.put(a[i], val)

Exemplo n.º 17
0
        return seg[0]

current_x = 0    
def segment_less(s1, s2):
    left1 = left_end(s1)
    right1 = right_end(s1)
    left2 = left_end(s2)
    right2 = right_end(s2)
    # I'm cheating by using division. -Jeremy
    m1 = (right1[1] - left1[1]) / (right1[0] - left1[0])
    m2 = (right2[1] - left2[1]) / (right2[0] - left2[0])
    y1 = left1[1] + m1 * (current_x - left1[0])
    y2 = left2[1] + m2 * (current_x - left2[0])
    return y1 < y2

T = BinarySearchTree(root=None, less=segment_less)

T.insert(((0 * 100, 173), (181, 370)))
T.insert(((7 * 100, 173), (181, 370)))
for n in range(1, 7):
    T.insert(((n * 100, 173), (181, 370)))
# T.insert(((291, 173), (181, 370)))
# T.insert(((432, 457), (391, 167)))
# T.insert(((297, 445), (338, 91)))
# T.insert(((169, 200), (436, 511)))
# T.insert(((168, 200), (436, 511)))
# T.insert(((168, 200), (435, 511)))

# segs = [((80, 156), (174, 427)), ((115, 154), (216, 425)), ((151, 152), (251, 415)), ((185, 149), (296, 409)), ((240, 146), (342, 395)), ((332, 145), (319, 409))]
# for s in segs:
#     T.insert(s)
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n")  # List containing 10000 names
f.close()

f = open('names_2.txt', 'r')
names_2 = f.read().split("\n")  # List containing 10000 names
f.close()

duplicates = []
#for name_1 in names_1:
#    for name_2 in names_2:
#        if name_1 == name_2:
#duplicates.append(name_1)

#Init BST
binary_search = BinarySearchTree(names_1[0])

#Add the names skip the 1st
for name in names_1[1:]:
    binary_search.insert(name)
for duplicate in names_2:
    if binary_search.contains(duplicate):
        duplicates.append(duplicate)

end_time = time.time()
print(f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print(f"runtime: {end_time - start_time} seconds")

# ---------- Stretch Goal -----------
# Python has built-in tools that allow for a very efficient approach to this problem
# What's the best time you can accomplish with no restrictions on techniques or data
            while tmp.right:
                tmp = tmp.right
            pre_succ.pre = tmp
        return

    if root.data < key:
        pre_succ.pre = root
        pre_succ(root.right, key)
    elif root.data > key:
        pre_succ.succ = root
        pre_succ(root.left, key)
    


if __name__ == '__main__':
    myTree = BinarySearchTree(6)
    insert(myTree, 7)
    insert(myTree, 5)
    insert(myTree, 13)
    insert(myTree, 3)
    insert(myTree, 9)
    insert(myTree, 12)    
    insert(myTree, 1)
    insert(myTree, 4)
    inorder(myTree)
    pre_succ.pre = None
    pre_succ.succ = None
    searchKey = 8
    pre_succ(myTree, searchKey)

    print("")