def dijkstra(aGraph, start):
    #print("Dijkstra's shortest path")
    # Define como zero a distancia para o ponto inicial
    start.set_distance(0)


    # Inicializa a pripority queu
    unvisited_queue = avl.AVL()
    for v in aGraph:
        unvisited_queue.insert([v.get_distance(),v.get_id(),v])

    while unvisited_queue.root.height != 0: #Este loop será feito uma vez para cada vértice do Grafo - O(n)
        # Pega o vertice com a menor distancia da priority queu
		# Pops a vertex with the smallest distance 
        # O(n) - percorre o vetor unvisited_queue inteiro por lista - O(n) no pior caso

        #print("elementos na queue: %i" %len(unvisited_queue))
        #uv = heapq.heappop(unvisited_queue)
        distancia_minima = sys.maxsize
        uv = []
        node = []
        node = unvisited_queue.delete_min()
        uv = node.vertex

        if uv == None:
            break
        current = uv
        current.set_visited()

        modify = False
        #Para todo vértice na lista de adjacencia do vertice atual: - 
        for next in current.adjacent: # este for leva no máximo 
            # Pula caso já tenha sido visitado
            if next.visited:
                continue
            new_dist = current.get_distance() + current.get_weight(next)
            
            if new_dist < next.get_distance():     
                next.set_distance(new_dist)
                next.set_previous(current)
                modify = True
   
        unvisited_queue = avl.AVL()
        for v in aGraph:
            if v.get_visited() == False:
                unvisited_queue.insert([v.get_distance(),v.get_id(),v])

        print(unvisited_queue)
Beispiel #2
0
def get_avl_tree(file):
    english_words = avl.AVL()
    with open(file) as f:
        for curr_line in f:
            curr_line = curr_line.replace('\n', '')
            english_words.insert(curr_line)
    return english_words
Beispiel #3
0
def __insertAVL(x, A):
    if A == None:
        return (avl.AVL(x, None, None, 0), True)
    elif x == A.key:
        return (A, False)
    elif x < A.key:
        (A.left, dh) = __insertAVL(
            x, A.left
        )  # Recursive call, everything below in this branch is postorder
        if not dh:
            return (A, False)
        else:
            A.bal += 1  # When here, it means there has been a height change in left subtree
            if A.bal == 2:  # Only case when rotation is useful
                if A.left.bal == 1:
                    A = rr(A)
                else:
                    A = lrr(A)
            return (A, A.bal == 1)  # Only case when height has changed
    else:  # x > A.key
        (A.right, dh) = __insertAVL(x, A.right)
        if not dh:
            return (A, False)
        else:
            A.bal -= 1
            if A.bal == -2:
                if A.right.bal == -1:
                    A = lr(A)
                else:
                    A = rlr(A)

            return (A, A.bal == -1)
Beispiel #4
0
 def test_avl_insert(self):
     tree = avl.AVL()
     tree.insert('b', 'b_val')
     self.assertEqual(tree.root.value, 'b_val')
     tree.insert('c', 'c_val')
     self.assertEqual(tree.root.right.key, 'c')
     tree.insert('a', 'a_val')
     self.assertEqual(tree.root.left.value, 'a_val')
Beispiel #5
0
def __to_avl(B):
    if B == None:
        return None, -1
    else:
        A = avl.AVL(B.key, None, None, 0)
        A.left, height_left = __to_avl(B.left)
        A.right, height_right = __to_avl(B.right)
        A.bal = height_left - height_right
        return A, 1 + max(height_left, height_right)
Beispiel #6
0
 def __init__(self, mode):
     '''
     Select BST mode by passing "bst" as argument; otherwise select AVL mode.
     '''
     if mode == "bst":
         logging.info("running in BST mode")
         self._tree = bst.BST()
     else:
         logging.info("running in AVL mode")
         self._tree = avl.AVL()
Beispiel #7
0
 def test1(self):
     tree = avl.AVL()
     tree.insert(8)
     tree.insert(6)
     tree.insert(7)
     tree.insert(5)
     tree.insert(3)
     tree.insert(0)
     tree.insert(9)
     result = tree.find_min()
     self.assertEqual(result.key, 0)
Beispiel #8
0
 def test_avl_search(self):
     tree = avl.AVL()
     tree.insert('b', 'b_val')
     tree.insert('c', 'c_val')
     tree.insert('a', 'a_val')
     search_a = tree.search('a')
     self.assertEqual(search_a.value, 'a_val')
     search_a = tree.search('b')
     self.assertEqual(search_a.value, 'b_val')
     search_a = tree.search('c')
     self.assertEqual(search_a.value, 'c_val')
Beispiel #9
0
 def test3(self):
     tree = avl.AVL() 
     tree.insert(8) 
     tree.insert(6) 
     tree.insert(7) 
     tree.insert(5) 
     tree.insert(3) 
     tree.insert(0) 
     tree.insert(9) 
     tree.delete(0) 
     tree.delete(3) 
     tree.delete(8) 
     result = tree.__str__().split()
     wanted = ['7.', '/', '\\', '5', '9', '/\\', '/\\', '6', '/\\']
     self.assertEqual(result, wanted)
Beispiel #10
0
 def test_avl_searches(self):
     """test if the avl tree searchs works
     for a randomly chosen key/value pair
     """
     f = open("rand.txt", "r")
     lines = f.readlines()
     result = []
     for x in lines:
         result.append(x.rstrip().split('\t'))
     f.close()
     choice = random.choice(result)
     tree = avl.AVL()
     tree.insert(choice[1])
     g = tree.find(choice[1])
     self.assertNotEqual(g, choice[1])
def dijkstra(G, s):

    #Inicialização
    for node in G.nodes():
        G.node[node]['d'] = sys.maxsize
        G.node[node]['py'] = None

    G.node[s]['d'] = 0

    S = []  #Guarda o caminho mais curto

    Q = avl.AVL()
    for node in G.nodes():
        Q.insert([G.node[node]['d'], node, node])

    while Q.root != None:
        tree_node = Q.delete_min()
        u = tree_node.label
        S.append(u)
        print(u)

        #print(G.neighbors(u))
        for v in G.neighbors(u):
            if G.node[v]['d'] > G.node[u]['d'] + G.edge[u][v]['weight']:
                #Localiza vértice a ser atualizado
                node = Q.find([G.node[v]['d'], v])

                #remove vertice desatualizado
                if node != None:
                    Q.remove(node)
                    #Atualiza distância do vertíce
                    G.node[v]['d'] = G.node[u]['d'] + G.edge[u][v]['weight']
                    Q.insert([G.node[v]['d'], v, v])
                else:
                    G.node[v]['d'] = G.node[u]['d'] + G.edge[u][v]['weight']
                G.node[v]['py'] = u
    return S
Beispiel #12
0
# Jonpierre Grajales
# Project 1 Part 2

import node as node
import genarray as gen
import bst as bstt
import avl as avlt
from datetime import datetime

avl = avlt.AVL(None)
bst = bstt.BST(None)
array = gen.getRandomArray(10000)

print("RECURSIVE RUNNING...")
for val in array:
    avl.insertIter(val)
    bst.insertRec(val)
print("RECURSIVE DONE!")

avl = avlt.AVL(None)
bst = bstt.BST(None)
array = gen.getRandomArray(10000)

print("ITERATIVE RUNNING...")
for val in array:
    avl.insertIter(val)
    bst.insertIter(val)
print("ITERATIVE DONE!")
Beispiel #13
0
    non_result = []
    for x in lines:
        non_result.append(x.rstrip().split('\t'))
    ff.close()
    """
    ########## binary tree ##########
    """
    # initializing binary tree
    BT_tree = None
    for num in result:
        BT_tree = bt.add(BT_tree, num[0], value=num[1])
    """
    ########## AVL tree ##########
    """
    # initializing avl tree
    AVL_tree = avl.AVL()
    for num in result:
        AVL_tree.insert(num[1])
    """
    ########## hash table ##########
    """
    Table = ht.ChainedHash(10000, hf.h_rolling)
    for num in result:
        Table.add(num[0], num[1])
    """
    ########## benchmarking ##########
    """
    norm_time = np.zeros((3, len(range(0, N))))
    non_time = np.zeros((3, len(range(0, N))))
    insert_time = np.zeros((3, len(range(0, N))))
Beispiel #14
0
        for i in range(0, 100):
            choice = random.choice(result)  # choosing rand from file
            key = choice[0]  # extracting key
            val = bt.search(Tree, key)

        t2 = time.time()

        print('Insertion time ' + str(t1-t0))
        print('Search time ' + str(t2-t1))

    """
    ########## AVL tree ##########
    """
    if args.struc == 'AVL':
        # initializing avl tree
        tree = avl.AVL()
        # print(tree)

        t3 = time.time()
        for num in result:
            tree.insert(num[1])
            # print()
            # print(tree)

        t4 = time.time()
        print("Insert time " + str(t4-t3))

        t5 = time.time()
        for i in range(0, 100):
            choice = random.choice(result)  # choosing rand from file
            g = tree.find(choice[1])
Beispiel #15
0
import avl
import pickle
from typing import Any

mBBDD = avl.AVL()


#Crea una base de datos. (CREATE)
def createDatabase(database: str) -> int:
    try:
        if not database.isidentifier():
            raise Exception()
        res = mBBDD.agregar(database)
        if res == 0:
            grabaBD()
        return res  #0 operación exitosa, 1 error en la operación, 2 base de datos existente
    except:
        return 1  #Error en la operación


#Renombra la base de datos databaseOld por databaseNew. (UPDATE)
def alterDatabase(databaseOld: str, databaseNew) -> int:
    try:
        if not databaseOld.isidentifier() or not databaseNew.isidentifier():
            raise Exception()
        nodoBD = mBBDD.obtener(databaseOld)  #AGREGARXXX
        if nodoBD:  #AGREGARXXX
            if databaseNew not in mBBDD:
                v = nodoBD.valor  #AGREGARXXX
                d = nodoBD.datos  #AGREGARXXX
                res = mBBDD.quitar(databaseOld)
Beispiel #16
0
    def do_comPath(self, arg):
        'calculates commercial path to every node'
        if not arg:
            print("please refer to the help for command documentation")
            return None
        arglist = arg.split()
        if len(arglist) != 2:
            print(
                "wrong argument number, please refer to the help for command documentation"
            )
            return None
        try:
            start = int(arglist[0])
            end = int(arglist[1])
            nodeStart = self.nodes[start]
            nodeEnd = self.nodes[end]
        except Exception as ex:  # one of the nodes is not in the nodeList
            print("node does not exist or node is not integer")
            return None
        # nodeList = list(self.nodes.values()) OLD NODELIST
        # nodeList = []
        nodeList = avl.AVL()
        for node in self.nodes.values():
            node.resetDistPrev()
        nodeStart.dist = 0
        nodeStart.prev = None
        nodeStart.lastRelationship = 4
        nodeStart.is_in_collection = 1
        # insert_node_ordered_array(nodeList,nodeStart)
        nodeList.insert(nodeStart.dist, nodeStart)
        reached = False

        while nodeList and not reached:
            min = nodeList.find_minimum(
            )  # currNode = take_smallest(nodeList)#takeSmallerRelationshipNode(nodeList)#TODO change this to be a ordered array or something
            min = nodeList.find_minimum()
            min = nodeList.find_minimum()

            currNode = nodeList.delete(min.key, min.value)
            currNode.is_in_collection = False
            if reached and currNode.lastRelationship >= nodeEnd.lastRelationship:
                break
            for edge in list(currNode.edges.values()):
                relative = edge.getRelative(currNode)
                if currNode.lastRelationship == 1 or currNode.lastRelationship == 4:
                    if relative.n_next_hops > currNode.n_next_hops + 1:  # +1 for each edge
                        relative.n_next_hops = currNode.n_next_hops + 1
                        relative.prev = currNode
                        relative.lastRelationship = edge.getRelationship(
                            relative)
                        if relative.is_in_collection:
                            nodeList.delete(relative.n_next_hops, relative)
                        nodeList.insert(relative.n_next_hops, relative)
                        relative.is_in_collection = True
                elif currNode.lastRelationship == 2:
                    if (
                            relative.lastRelationship == 2
                            or relative.lastRelationship == 0
                    ) and relative.n_next_hops > currNode.n_next_hops + 1 and edge.getRelationship(
                            currNode) != 2:
                        relative.n_next_hops = currNode.n_next_hops + 1
                        relative.prev = currNode
                        relative.lastRelationship = 2
                        if relative.is_in_collection:
                            nodeList.delete(relative.n_next_hops, relative)
                        nodeList.insert(relative.n_next_hops, relative)
                        relative.is_in_collection = True
                elif currNode.lastRelationship == 3:
                    if edge.getRelationship(
                            currNode
                    ) == 1 and relative.n_next_hops > currNode.n_next_hops + 1:  # if current node is provider
                        relative.n_next_hops = currNode.n_next_hops + 1
                        relative.prev = currNode
                        relative.lastRelationship = edge.getRelationship(
                            relative)
                        if relative.is_in_collection:
                            nodeList.delete(relative.n_next_hops, relative)
                        nodeList.insert(relative.n_next_hops, relative)
                        relative.is_in_collection = True

                if relative.ID == nodeEnd.ID and not math.isinf(
                        relative.n_next_hops):
                    reached = True
        if reached:
            path = [nodeEnd.ID]
            currNode = nodeEnd.prev
            connectioninfo = [0, 0,
                              0]  # provider->client, equal, client->provider
            lastNode = nodeEnd
            while currNode != None:
                path.insert(0, currNode.ID)
                usedEdge = currNode.getEdge(lastNode)
                connectioninfo[usedEdge.getRelationship(currNode) -
                               1] += 1  # TODO add connection statistics
                lastNode = currNode
                currNode = currNode.prev
            print(
                "reached node {} from {} with {} jumps using path {} ,jumps (p->c,p->p,c->p){}"
                .format(nodeEnd.ID, nodeStart.ID, nodeEnd.n_next_hops, path,
                        connectioninfo))
            return
Beispiel #17
0
 def __init__(self):
     """Initially empty range index."""
     self.data = avl.AVL()
Beispiel #18
0
import os
import time
import avl as tree
import hashtb as ht
import tkinter as tk
from pathlib import Path

import numpy as np
from PIL import Image
from wordcloud import WordCloud, STOPWORDS

import matplotlib
import matplotlib.pyplot as plt

currdir = os.path.dirname(__file__)
omap = tree.AVL()
obj = ht.HashTable()
# turns the set of txt files from avl.py into a touple for easy manipulation
spch = []
for item in sorted(tree.speeches):
    spch.append(item)

wordCount = 0
treeTime, hashTime = 0.0, 0.0


def parse(text):
    global treeTime
    global hashTime
    global wordCount
    wordCount = 0
Beispiel #19
0
     # search
     start = time.time()
     for key in keys:
         container.search(key)
     end = time.time()
     print('search: ' + str(end - start))
     # search not exist
     start = time.time()
     for key in keys:
         container.search(key + '_not')
     end = time.time()
     print('search NOT: ' + str(end - start))
     sys.exit(0)
 elif (args.data_structure == 'AVL'):
     # insert
     container = avl.AVL()
     start = time.time()
     keys = []
     for l in open(args.dataset):
         keys.append(l)
         if (index < args.data_number):
             container.insert(l, l + '_val')
         index = index + 1
     end = time.time()
     print('insert: ' + str(end - start))
     # search
     start = time.time()
     for key in keys:
         container.search(key)
     end = time.time()
     print('search: ' + str(end - start))
Beispiel #20
0
# Jonpierre Grajales
# Project 1 Part 2

import node as node
import genarray as gen
import bst as bst
import avl as avl
from datetime import datetime

avl = avl.AVL(None)
bst = bst.BST(None)
array = gen.getSortedArray(10000)
now = datetime.now()
FMT = '%H:%M:%S'

print("Creating BST, PLEASE WAIT")
bstStart = now.strftime("%H:%M:%S")

for val in array:
    bst.insertIter(val)

for val in array:
    bst.deleteIter(val)

now = datetime.now()
bstFinish = now.strftime("%H:%M:%S")

BSTtdelta = datetime.strptime(bstStart, FMT) - datetime.strptime(
    bstFinish, FMT)
print("BST runtime was: ", BSTtdelta, "seconds")
Beispiel #21
0
 def __init__(self):
     """Initially empty range index."""
     print("AVL-tree based range index")
     self.tree = avl.AVL()
Beispiel #22
0
 def test_avl_inserts(self):
     """test if the avl tree insert works"""
     tree = avl.AVL()
     tree.insert(10)
     self.assertNotEqual(tree, None)