def test_top_pop(): """ Este test prueba la creacion de una cola y que el orden de salida sea el correcto para la estructura en cuestion, y que el tamaño se reduzca para cada salida de objeto """ stack = st.newStack(list_type) assert st.size(stack) == 0 assert st.isEmpty(stack) st.push(stack, book5) st.push(stack, book6) st.push(stack, book3) st.push(stack, book10) st.push(stack, book1) st.push(stack, book2) st.push(stack, book8) st.push(stack, book4) st.push(stack, book7) st.push(stack, book9) total = st.size(stack) while not (st.isEmpty(stack)): top = st.top(stack) assert (st.pop(stack) == top) total -= 1 assert (total == st.size(stack))
def PesoDeLaLista(lista): A = 0 while stack.size(lista) != 0: b = (stack.pop(lista)) n = b["weight"] A += float(n) return A
def ListaConID(lista): A = [] while stack.size(lista) != 0: B = (stack.pop(lista)) N = B["vertexB"] A.append(N) return A
def printReq3(pila): i = 1 tamano = stack.size(pila) while i <= tamano: cable = stack.pop(pila) print('Desde ', cable['vertexA'].split('-')[0], ' hasta ', cable['vertexB'].split('-')[0], ' con una distancia de ', cable['weight']) i+=1
def requerimiento_4(analyzer,station,resistance): try: resistance=resistance*60 recorrido= bfs.BreadhtFisrtSearch(analyzer['connections'],station) size= gr.numVertices(analyzer['connections']) vertexxx= gr.vertices(analyzer['connections']) dicc= {} for i in range(1,size): ids= lt.getElement(vertexxx,i) vertice= m.get(analyzer['coordinates_destiny'],ids)['value']['name'] if bfs.hasPathTo(recorrido,ids): path= bfs.pathTo(recorrido,ids) sizep= st.size(path) if sizep != 1 : init= st.pop(path) summ= 0 dicc[vertice]= [] while sizep >= 2: vertex2= st.pop(path) if vertex2 is None : break arco= gr.getEdge(analyzer['connections'],init,vertex2) summ+= arco['weight'] init= vertex2 if summ > resistance : dicc[str(vertice)]= None else: dicc[str(vertice)].append(poner_bonita_la_ruta(analyzer,arco)) return dicc except Exception as exp: error.reraise(exp, 'model;Req_4')
def findShortestPath(analyzer, pais1, pais2): delta_time = -1.0 delta_memory = -1.0 tracemalloc.start() start_time = getTime() start_memory = getMemory() answer = model.findShortestPath(analyzer, pais1, pais2) path = [] while st.size(answer[0]) > 0: step = st.pop(answer[0]) path.append({ 'origin': step['vertexA'], 'destination': step['vertexB'], 'distance': step['weight'] }) stop_memory = getMemory() stop_time = getTime() tracemalloc.stop() delta_time = stop_time - start_time delta_memory = deltaMemory(start_memory, stop_memory) return analyzer, path, answer[1], delta_time, delta_memory
def routeByResistance(citibike, initialStation, resistanceTime): try: dijsktra = djk.Dijkstra(citibike["connections"], initialStation) vertices = gr.vertices(citibike["connections"]) iterator = it.newIterator(vertices) trueStations = st.newStack() stops = m.newMap(numelements=768, maptype="CHAINING", loadfactor=1, comparefunction=compareStopIds) while it.hasNext(iterator): element = it.next(iterator) if element != initialStation and djk.hasPathTo(dijsktra, element) is True: if m.get(stops, element) is None or getElement(m.get(stops, element))["value"] is False: if djk.distTo(dijsktra,element) <= resistanceTime: pila= djk.pathTo(dijsktra,element) pila2 = djk.pathTo(dijsktra,element) size_pila = 0 repetition = False lon_pila = st.size(pila) watcher = {"value": True} while size_pila < lon_pila and repetition == False: pop = st.pop(pila)["vertexB"] if m.get(stops,pop) is None or getElement(m.get(stops,pop))["value"] is False: m.put(stops,pop,watcher) else: repetition = True watcher["value"]=False size_pila +=1 if repetition == False: st.push(trueStations, pila2) return trueStations except: return None
def test_dfo(graph): search = dfo.DepthFirstOrder(graph) assert stack.size(search['reversepost']) == 10 print('') while not stack.isEmpty(search['reversepost']): top = stack.pop(search['reversepost']) print(top)
def printReq3(analyzer, paisB): path = controller.minimumCostPath(analyzer, paisB) if path is not None: distancia = 0 for relacion in lt.iterator(path): coordenadasVertexA = (controller.getDistanceREQ3( analyzer, relacion['vertexA'])) coordenadasVertexB = (controller.getDistanceREQ3( analyzer, relacion['vertexB'])) valorDistancia = controller.haversine(coordenadasVertexA, coordenadasVertexB) distancia += valorDistancia print("\n{0} ==> {1}\tDistancia(km): {2}".format( relacion['vertexA'], relacion['vertexB'], valorDistancia)) pathlen = stack.size(path) print(f"\nEl camino es de longitud: {pathlen}") print(f"\nLa distancia total de la ruta es: {distancia} km.") return path else: print('\nNo existe un camino.')
def optionSix(cont, destStation): delta_time = -1.0 tracemalloc.start() start_time = getTime() jose = m.newMap() path = controller.minimumCostPath(cont, destStation) if path is not None: pathlen = stack.size(path) while (not stack.isEmpty(path)): stop = stack.pop(path) if m.contains(jose, stop['vertexB']) == False: m.put(jose, stop['vertexB'], 1) pacho = m.keySet(jose) arias = lt.size(pacho) print('Numero de vertices: ' + str(arias)) print("El numero de arcos es: ", pathlen) else: print('No hay camino') stop_time = getTime() tracemalloc.stop() delta_time = stop_time - start_time print("Tiempo [ms]: ", f"{delta_time:.3f}")
def getBestSchedule(graph, pickUp, dropOff, InitialTime, EndTime): bestSchedule = InitialTime currentStamp = InitialTime first = getTime(graph, pickUp, dropOff, currentStamp) bestTime = first[0] search = first[1] while currentStamp != EndTime: currentStamp = add15(currentStamp) time = getTime(graph, pickUp, dropOff, currentStamp) if time[0] < bestTime: bestSchedule = currentStamp bestTime = time[0] search = time[1] path = [] pathTo = djk.pathTo(search, dropOff) if pathTo is None: path = None else: while not st.isEmpty(pathTo): edge = st.pop(pathTo) Com = edge["vertexA"] path.append(Com) if st.size(pathTo) == 0: Com2 = edge["vertexB"] path.append(Com2) return bestSchedule, path, bestTime
def optionSix(): path = controller.routeByResistance(cont, initialStation, resistanceTime) if path is None: print("La ruta que introdujiste no existe.") else: if stack.isEmpty(path) is False: for i in range(0, stack.size(path)): print("\nRuta", i + 1) sub_pila = stack.pop(path) for j in range(0, stack.size(sub_pila)): edge = stack.pop(sub_pila) print("Segmento", j + 1) print("Entre", edge["vertexA"], "y", edge["vertexB"], "te demoras", float(edge["weight"]) / 60, "minutos") else: print("No hay ninguna ruta para ese tiempo estipulado")
def hayarEstaciones(cont, initialStation): informacion = gr.adjacents(cont["connections"], initialStation) lista=[] if stack.isEmpty(informacion) == False: for i in range(0, stack.size(informacion)): sub_pila = stack.pop(informacion) lista.append(sub_pila) return lista
def optionSix(): path = controller.minimumCostPath(cont, destStation) if path is not None: pathlen = stack.size(path) print('El camino es de longitud: ' + str(pathlen)) while (not stack.isEmpty(path)): stop = stack.pop(path) print(stop) else: print('No hay camino')
def test_top_pop(stack, books): assert st.size(stack) == 0 assert st.isEmpty(stack) st.push(stack, books[5]) st.push(stack, books[6]) st.push(stack, books[3]) st.push(stack, books[10]) st.push(stack, books[1]) st.push(stack, books[2]) st.push(stack, books[8]) st.push(stack, books[4]) st.push(stack, books[7]) st.push(stack, books[9]) total = st.size(stack) while not (st.isEmpty(stack)): top = st.top(stack) assert (st.pop(stack) == top) total -= 1 assert (total == st.size(stack))
def req3(analyzer,pais1,pais2): delta_time = -1.0 delta_memory = -1.0 tracemalloc.start() start_time = getTime() start_memory = getMemory() capital1=model.capital(analyzer,pais1.lower()) capital2=model.capital(analyzer,pais2.lower()) if capital1==None or capital2==None: print('No hay información para los países dados.') else: distpath=model.distpath(analyzer,capital1,capital2) distancia=distpath[0] path = distpath[1] print('\nLa distancia total de la ruta es de: '+str(distancia)+' km.') print('\nLa ruta está dada por: ') i = 1 inicial = st.size(path) while i<=inicial: sub = st.pop(path) if i == 1: vertexA = (sub["vertexA"][0]).capitalize() + ", " + (str(pais1)).capitalize() cableA = "CAPITAL" else: place = mp.get(analyzer["name_dado_id"], sub["vertexA"][0]) if place != None: vertexA = place["value"] cableA = str(sub["vertexA"][1]) else: vertexA = sub["vertexA"][0] cableA = "CAPITAL" place = mp.get(analyzer["name_dado_id"], sub["vertexB"][0]) if place != None: vertexB = place["value"] else: vertexB = sub["vertexB"][0].upper() if i>1: print("-------------------------------------------------------------") else: print('') print(str(vertexA) + " ——> " + str(vertexB) +" || CABLE: "+ cableA +str(" || DISTANCIA (km): ") +str(sub["weight"])) i += 1 stop_memory = getMemory() stop_time = getTime() tracemalloc.stop() delta_time = stop_time - start_time delta_memory = deltaMemory(start_memory, stop_memory) return delta_time,delta_memory
def print_Req3(camino): if camino is not None: distCamino = stk.size(camino) longitud = 0 while (not stk.isEmpty(camino)): cada_vertice = stk.pop(camino) longitud += cada_vertice['weight'] print(cada_vertice) print('El camino es de longitud [km]: ' + str(longitud) + '.') else: print('No hay camino.')
def test_sizeStack(): """ Se prueba la creacion de una cola y la relacion con el tamaño al ingresar datos """ stack = st.newStack(list_type) assert (st.size(stack) == 0) assert (st.isEmpty(stack)) st.push(stack, book5) st.push(stack, book6) st.push(stack, book3) st.push(stack, book10) st.push(stack, book1) st.push(stack, book2) st.push(stack, book8) st.push(stack, book4) st.push(stack, book7) st.push(stack, book9) assert st.size(stack) == 10
def test_error_pop(): """ Este test busca comprobar que es imposible eliminar un objeto de una pila vacia """ stack = st.newStack(list_type) assert (st.size(stack) == 0) assert (st.isEmpty(stack)) with pytest.raises(Exception): st.pop(stack)
def optionSix(cont, destStation): respuesta = controller.minimumCostPath(cont, destStation) path = respuesta[1] if path is not None: pathlen = stack.size(path) print('El camino es de longitud: ' + str(pathlen)) while (not stack.isEmpty(path)): stop = stack.pop(path) print(stop) print("Tiempo [ms]: " + str(respuesta[0])) else: print('No hay camino')
def optionSix(cont, destStation): path1 = controller.minimumCostPath(cont, destStation) path = path1[1] if path is not None: pathlen = stack.size(path) print('El camino es de longitud: ' + str(pathlen)) while (not stack.isEmpty(path)): stop = stack.pop(path) print(stop) else: print('No hay camino') print('Tiempo de ejecucion:', ((path1[0]) / 1000))
def test_infoElements(stack, books): assert (st.size(stack) == 0) assert (st.isEmpty(stack)) st.push(stack, books[5]) st.push(stack, books[6]) st.push(stack, books[3]) st.push(stack, books[10]) st.push(stack, books[1]) st.push(stack, books[2]) st.push(stack, books[8]) st.push(stack, books[4]) st.push(stack, books[7]) st.push(stack, books[9]) elem = st.top(stack) assert (st.size(stack) == 10) assert (elem == books[9]) elem = st.pop(stack) assert (st.size(stack) == 9) assert (elem == books[9]) elem = st.pop(stack) assert (st.size(stack) == 8) assert (elem == books[7]) elem = st.top(stack) assert (st.size(stack) == 8) assert (elem == books[4]) st.push(stack, books[9]) assert (st.size(stack) == 9) elem = st.top(stack) assert (elem == books[9])
def turistInteres(citibike, latitudActual, longitudActual, latitudDestino, longitudDestino): """ Estacion mas cercana a la posicion actual, Estacion mas cercana al destino, (Menor) Tiempo estimado, Lista de estaciones para llegar al destino """ actualNearStationID = destinyNearStationID = None coords = citibike['coords'] actualNear = destinyNear = float('INF') keyList = m.keySet(coords) #Conseguir las estaciones mas cercanas al destino for i in range(m.size(coords)): key = lt.getElement(keyList, i) lat, lon, s_e = m.get(coords, key)['value'] lat = float(lat) lon = float(lon) distanceToActual = distance(lat, lon, latitudActual, longitudActual) distanceToDestiny = distance(lat, lon, latitudDestino, longitudDestino) #s_e esta para verificar que sea entrada o salida if distanceToActual < actualNear and s_e == 0: actualNear = distanceToActual actualNearStationID = key if distanceToDestiny < destinyNear and s_e == 1: destinyNear = distanceToDestiny destinyNearStationID = key #Obtener el nombre actualNearStation = getStation(citibike, actualNearStationID) destinyNearStation = getStation(citibike, destinyNearStationID) #Usar Dijsktra para conseguir el resto de info structureActual = djk.Dijkstra(citibike['connections'], actualNearStationID) if djk.hasPathTo(structureActual, destinyNearStationID): tripTime = djk.distTo(structureActual, destinyNearStationID) stationStack = djk.pathTo(structureActual, destinyNearStationID) else: return (actualNearStation, destinyNearStation, float('INF'), None) #De stack a lista con la informacion pulida stationList = lt.newList(datastructure='ARRAY_LIST') for i in range(st.size(stationStack)): stationD = st.pop(stationStack) vA = getStation(citibike, stationD["vertexA"])[1] vB = getStation(citibike, stationD["vertexB"])[1] lt.addLast(stationList, (vA, vB)) return actualNearStation, destinyNearStation, tripTime, stationList
def MST(analyzer): analyzer['MST'] = prim.PrimMST(analyzer['connections_distancia']) suma = 0 contador = 0 for i in lt.iterator(m.valueSet(analyzer['MST']['distTo'])): suma += i contador += 1 analyzer['Dij'] = djk.Dijkstra( analyzer['connections_distancia'], lt.getElement(gr.vertices(analyzer['connections_distancia']), 5)) maximo = None distancia = 0 for vertice in lt.iterator(gr.vertices(analyzer['connections_distancia'])): camino = djk.pathTo(analyzer['Dij'], vertice) if camino != None: if st.size(camino) > distancia and distancia != math.inf: maximo = camino distancia = st.size(camino) camino_final = lt.newList() for conexion in lt.iterator(camino): try: int(conexion['vertexA'][0]) verticea = conexion['vertexA'][0] pareja1 = m.get(analyzer['landing_points'], verticea) nombrea = me.getValue(pareja1)['name'].split(',')[0] except: nombrea = conexion['vertexA'][0] try: int(conexion['vertexB'][0]) verticeb = conexion['vertexB'][0] pareja2 = m.get(analyzer['landing_points'], verticeb) nombreb = me.getValue(pareja2)['name'].split(',')[0] except: nombreb = conexion['vertexB'][0] conexion = (nombrea, nombreb, conexion['weight']) lt.addLast(camino_final, conexion) return (contador, suma, camino_final)
def optionSix(cont, destStation): ti = time.time() path = controller.minimumCostPath(cont, destStation) if path is not None: pathlen = stack.size(path) print('El camino es de longitud: ' + str(pathlen)) while (not stack.isEmpty(path)): stop = stack.pop(path) print(stop) else: print('No hay camino') tf = time.time() print('Tiempo de ejecución:', tf - ti)
def optionSix(cont, destStation): path = controller.minimumCostPath(cont, destStation) if path[0] is not None: pathlen = stack.size(path[0]) print('El camino es de longitud: ' + str(pathlen)) while (not stack.isEmpty(path[0])): stop = stack.pop(path[0]) print(stop) print("*** Medidas de tiempo y espacio ***") print("Tiempo [ms]: ", f"{path[1]:.3f}", " || ", "Memoria [kB]: ", f"{path[2]:.3f}") else: print('No hay camino')
def optionFive(): lcao = controller.getstationsinrange(cont, cao, rti, rtf) mruta = controller.getbestroute(cont, lcao, cad) print("El mejor horario (hora:minutos) de inicio de viaje: ", mruta) controller.minimumCostPaths(cont, cao) path = controller.minimumCostPath(cont, cad) if path is not None: pathlen = stack.size(path) print('El camino es de longitud: ' + str(pathlen)) while (not stack.isEmpty(path)): stop = stack.pop(path) print(stop) else: print('No hay camino')
def BuscarRutaMasCorta(analyzer, rangoA, rangoB, origen, destino): A = model.RutaMasRapida(analyzer, rangoA, rangoB, origen, destino) Inicio = stack.pop(A[0])["vertexA"].split("-") Duracion = A[1] print("Ruta de viaje: ") while stack.size(A[0]) > 1: B = stack.pop(A[0])["vertexA"].split("-") print(B[0]) print("------") n = stack.pop(A[0])["vertexB"].split("-") print(n[0]) print("-----------------------------------------") print("Partida del area",Inicio[0],"a la hora",Inicio[1]) print("Duracion en minutos del viaje",str(float(Duracion)/60))
def test_pushElements(stack, books): st.push(stack, books[5]) st.push(stack, books[6]) st.push(stack, books[3]) st.push(stack, books[10]) st.push(stack, books[1]) st.push(stack, books[2]) st.push(stack, books[8]) st.push(stack, books[4]) st.push(stack, books[7]) st.push(stack, books[9]) assert st.size(stack) == 10 while not st.isEmpty(stack): element = st.pop(stack) print(element)
def optionSix(cont, destStation): start_time = time.perf_counter() path = controller.minimumCostPath(cont, destStation) if path is not None: pathlen = stack.size(path) print('El camino es de longitud: ' + str(pathlen)) while (not stack.isEmpty(path)): stop = stack.pop(path) print(stop) else: print('No hay camino') end_time = time.perf_counter() operation_time = end_time - start_time print(operation_time * 1000)