def newMap(numelements, prime, loadfactor, cmpfunction, ints): """Crea una tabla de simbolos (map) sin orden Crea una tabla de hash con capacidad igual a nuelements (primo mas cercano al doble de numelements). prime es un número primo utilizado para el cálculo de los codigos de hash, si no es provisto se utiliza el primo 109345121. Args: numelements: Tamaño inicial de la tabla prime: Número primo utilizado en la función MAD loadfactor: Factor de carga inicial de la tabla comparefunction: Funcion de comparación entre llaves Returns: Un nuevo map Raises: Exception """ capacity = nextPrime(numelements//loadfactor) scale = rd.randint(1, prime-1) + 1 shift = rd.randint(1, prime) table = lt.newList('ARRAY_LIST', cmpfunction) for _ in range(capacity): bucket = lt.newList('SINGLE_LINKED', cmpfunction) lt.addLast(table, bucket) hashtable = {'prime': prime, 'capacity': capacity, 'scale': scale, 'shift': shift, 'table': table, 'ints': ints, 'size': 0, 'comparefunction': cmpfunction, 'type': 'CHAINING'} return hashtable
def newHeap(size, cmpfunction): """ Crea un nuevo heap basado en un arreglo, cuyo primer elemento es inicializado en None y no será utilizado Args: cmpfunction: La funcion de comparacion size: El numero de elementos Returns: El heap Raises: Exception """ try: heap = { 'elements': None, 'size': 0, 'offset': 2, 'cmpfunction': cmpfunction } heap['elements'] = lt.newList(datastructure='ARRAY_LIST', cmpfunction=cmpfunction) lt.addLast(heap['elements'], None) return heap except Exception as exp: error.reraise(exp, 'newHeap')
def adjacents(graph, vertex): """ Retorna una lista con todos los vertices adyacentes al vertice vertex Args: graph: El grafo sobre el que se ejecuta la operacion vertex: El vertice del que se quiere la lista Returns: La lista de adyacencias Raises: Exception """ try: element = map.get(graph['vertices'], vertex) lst = element['value'] lstresp = lt.newList() iter = it.newIterator(lst) while (it.hasNext(iter)): edge = it.next(iter) v = e.either(edge) if (v == vertex): lt.addLast(lstresp, e.other(edge, v)) else: lt.addLast(lstresp, v) return lstresp except Exception as exp: error.reraise(exp, 'ajlist:adjacents')
def rehash(map): """ Se aumenta la capacidad de la tabla al doble y se hace rehash de todos los elementos de la tabla. """ try: newtable = lt.newList("ARRAY_LIST", map["comparefunction"]) capacity = nextPrime(map["capacity"] * 2) for _ in range(capacity): entry = me.newMapEntry(None, None) lt.addLast(newtable, entry) oldtable = map["table"] map["size"] = 0 map["currentfactor"] = 0 map["table"] = newtable map["capacity"] = capacity for pos in range(lt.size(oldtable)): entry = lt.getElement(oldtable, pos + 1) if entry["key"] is not None and entry["key"] != "__EMPTY__": hash = hashValue(map, entry["key"]) pos = findSlot(map, entry["key"], hash, map["comparefunction"]) lt.changeInfo(map["table"], abs(pos), entry) if pos < 0: map["size"] += 1 map["currentfactor"] = map["size"] / map["capacity"] return map except Exception as exp: error.reraise(exp, "Probe:rehash")
def rehash(map): """ Se aumenta la capacidad de la tabla al doble y se hace rehash de todos los elementos de la tabla. """ try: newtable = lt.newList('ARRAY_LIST', map['comparefunction']) capacity = nextPrime(map['capacity'] * 2) for _ in range(capacity): entry = me.newMapEntry(None, None) lt.addLast(newtable, entry) oldtable = map['table'] map['size'] = 0 map['currentfactor'] = 0 map['table'] = newtable map['capacity'] = capacity for pos in range(lt.size(oldtable)): entry = lt.getElement(oldtable, pos + 1) if (entry['key'] is not None and entry['key'] != '__EMPTY__'): hash = hashValue(map, entry['key']) pos = findSlot(map, entry['key'], hash, map['comparefunction']) lt.changeInfo(map['table'], abs(pos), entry) if (pos < 0): map['size'] += 1 map['currentfactor'] = map['size'] / map['capacity'] return map except Exception as exp: error.reraise(exp, 'Probe:rehash')
def getEdge(graph, vertexa, vertexb): """ Retorna el arco asociado a los vertices vertexa ---- vertexb Args: graph: El grafo sobre el que se ejecuta la operacion vertexa: Vertice de inicio vertexb: Vertice destino Returns: El arco que une los verices vertexa y vertexb Raises: Exception """ try: element = map.get(graph['vertices'], vertexa) lst = element['value'] itvertex = it.newIterator(lst) edges = lt.newList(datastructure='SINGLE_LINKED', cmpfunction=None) while (it.hasNext(itvertex)): edge = it.next(itvertex) if (graph['directed']): if (e.either(edge) == vertexa and (e.other(edge, e.either(edge)) == vertexb)): return edge elif (e.either(edge) == vertexa or (e.other(edge, e.either(edge)) == vertexb)): lt.addLast(edges, edge) return edges except Exception as exp: error.reraise(exp, 'ajlist:getedge')
def edges(graph): """ Retorna una lista con todos los arcos del grafo graph Args: graph: El grafo sobre el que se ejecuta la operacion Returns: Una lista con los arcos del grafo Raises: Exception """ try: lstmap = map.valueSet(graph['vertices']) itervertex = it.newIterator(lstmap) lstresp = lt.newList('SINGLE_LINKED', e.compareedges) while it.hasNext(itervertex): lstedge = it.next(itervertex) iteredge = it.newIterator(lstedge) while (it.hasNext(iteredge)): edge = it.next(iteredge) if (graph['directed']): lt.addLast(lstresp, edge) elif (not lt.isPresent(lstresp, edge)): lt.addLast(lstresp, edge) return lstresp except Exception as exp: error.reraise(exp, 'ajlist:edges')
def newIndexHeap(cmpfunction): """ Crea un cola de prioridad indexada orientada a menor Args: cmpfunction: La funcion de comparacion size: El numero de elementos Returns: Una nueva cola de prioridad indexada Raises: Exception """ try: indexheap = {'elements': None, 'qpMap': None, 'size': 0, 'cmpfunction': cmpfunction} indexheap['elements'] = lt.newList(datastructure='ARRAY_LIST', cmpfunction=cmpfunction) indexheap['qpMap'] = map.newMap( maptype='PROBING', comparefunction=cmpfunction ) return indexheap except Exception as exp: error.reraise(exp, 'indexheap:newindexheap')
def newList(datastructure='SINGLE_LINKED', cmpfunction=None): """Crea una lista vacia Args: cmpfunction: Función de comparación para los elementos de la lista Returns: Una nueva lista Raises: Exception """ try: lst = lt.newList(datastructure, cmpfunction) return lst except Exception as exp: error.reraise(exp, 'TADList->newList: ')
def valueSet(map): """ Retorna una lista con todos los valores de la tabla de hash Args: map: El map Returns: lista de valores Raises: Exception """ ltset = lt.newList() for pos in range(lt.size(map['table'])): entry = lt.getElement(map['table'], pos + 1) if (entry['value'] is not None and entry['value'] != '__EMPTY__'): lt.addLast(ltset, entry['value']) return ltset
def valueSet(map): """ Retorna una lista con todos los valores de la tabla de hash Args: map: El map Returns: lista de valores Raises: Exception """ ltset = lt.newList('SINGLE_LINKED', map['comparefunction']) for pos in range(lt.size(map['table'])): bucket = lt.getElement(map['table'], pos + 1) for element in range(lt.size(bucket)): entry = lt.getElement(bucket, element + 1) lt.addLast(ltset, entry['value']) return ltset
def isEmpty(map): """ Informa si la tabla de hash se encuentra vacia Args: map: El map Returns: True: El map esta vacio False: El map no esta vacio Raises: Exception """ bucket = lt.newList() empty = True for pos in range(lt.size(map['table'])): bucket = lt.getElement(map['table'], pos + 1) if lt.isEmpty(bucket) is False: empty = False break return empty
def newMap(numelements, prime, loadfactor, comparefunction): """Crea una tabla de simbolos (map) sin orden Crea una tabla de hash con capacidad igual a nuelements (primo mas cercano al doble de numelements). prime es un número primo utilizado para el cálculo de los codigos de hash, si no es provisto se utiliza el primo 109345121. Args: numelements: Tamaño inicial de la tabla prime: Número primo utilizado en la función MAD loadfactor: Factor de carga maximo de la tabla comparefunction: Funcion de comparación entre llaves Returns: Un nuevo map Raises: Exception """ try: capacity = nextPrime(numelements // loadfactor) scale = rd.randint(1, prime - 1) + 1 shift = rd.randint(1, prime) table = lt.newList('ARRAY_LIST', comparefunction) for _ in range(capacity): entry = me.newMapEntry(None, None) lt.addLast(table, entry) hashtable = { 'prime': prime, 'capacity': capacity, 'scale': scale, 'shift': shift, 'table': table, 'currentfactor': 0, 'limitfactor': loadfactor, 'comparefunction': comparefunction, 'size': 0, 'type': 'PROBING' } return hashtable except Exception as exp: error.reraise(exp, 'Probe:newMap')
def keySet(map): """ Retorna una lista con todas las llaves de la tabla de hash Args: map: El map Returns: lista de llaves Raises: Exception """ try: ltset = lt.newList() for pos in range(lt.size(map['table'])): entry = lt.getElement(map['table'], pos + 1) if (entry['key'] is not None and entry['key'] != '__EMPTY__'): lt.addLast(ltset, entry['key']) return ltset except Exception as exp: error.reraise(exp, 'Probe:keyset')
def insertVertex(graph, vertex): """ Inserta el vertice vertex en el grafo graph Args: graph: El grafo sobre el que se ejecuta la operacion vertex: El vertice que se desea insertar Returns: El grafo graph con el nuevo vertice Raises: Exception """ try: edges = lt.newList() map.put(graph['vertices'], vertex, edges) if (graph['directed']): map.put(graph['indegree'], vertex, 0) return graph except Exception as exp: error.reraise(exp, 'ajlist:insertvertex')
def valueSet(map): """ Retorna una lista con todos los valores de la tabla de hash Args: map: El map Returns: lista de valores Raises: Exception """ try: ltset = lt.newList("ARRAY_LIST") for pos in range(lt.size(map["table"])): entry = lt.getElement(map["table"], pos + 1) if entry["value"] is not None and entry["value"] != "__EMPTY__": lt.addLast(ltset, entry["value"]) return ltset except Exception as exp: error.reraise(exp, "Probe:valueset")
def getDateInfo(dateOmap, date): """ Para una fecha devuelve una lista de la cantidad de accidentes por severidad y el total de accidentes Args: dateOmap: Order map organizado por fechas date: datetime de la fecha Returns: Entry con la lista y el total """ dateRoot = om.get(dateOmap, date) if dateRoot is None: return None dateEntry = dateRoot['value'] severityList = Op.operationSetMap(dateEntry['SeverityIndex'], Aux.makeListMp, newList('ARRAY_LIST')) severityListAndTotal = { 'list': severityList, 'total': dateEntry['numAccidents'] } return severityListAndTotal
def newList(datastructure=None, cmpfunction=None, key=None, filename=None, delimiter=","): """Crea una lista vacia Args: datastructure: Tipo de estructura de datos a utilizar para implementar la lista. Los tipos posibles pueden ser: ARRAY_LIST y SINGLE_LINKED. cmpfunction: Función de comparación para los elementos de la lista. Si no se provee función de comparación se utiliza la función por defecto pero se debe proveer un valor para key. Si se provee una función de comparación el valor de Key debe ser None. Key: Identificador utilizado para comparar dos elementos de la lista con la función de comaparación por defecto. filename: Si se provee este valor, se crea una lista a partir de los elementos encontrados en el archivo. Se espera que sea un archivo CSV UTF8. delimiter: Si se pasa un archivo en el parámetro filename, se utiliza este valor para separar los campos. El valor por defecto es una coma. Returns: Una nueva lista Raises: Exception """ try: lst = lt.newList(datastructure, cmpfunction, key, filename, delimiter) return lst except Exception as exp: error.reraise(exp, 'TADList->newList: ')
def MakeListFormat(Type='ARRAY_LIST'): return {'list': newList(Type), 'total': 0}
stop=False while (rs in range(1, size)) and (ls in range(1,size)) and not stop: root=lt.getElement(lst,follower) Right_son=lt.getElement(lst, rs) Left_son=lt.getElement(lst, ls) if cmpfunction(root, Right_son): lt.exchange(lst, follower, rs) if cmpfunction(Right_son, Left_son): lt.exchange(lst, follower, ls) follower=rs elif cmpfunction(root, Left_son): lt.exchange(lst, follower, ls) follower=ls else: stop=True rs=follower*2 ls=follower*2+1 example=hp.newHeap(cmpfunction) lst=lt.newList() def cmpfunction(a,b ): """ Compara dos números. """ if a < b: return -1 elif a == b: return 0 else: return 1