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 addBike(citibike, origin, destination, duration, bike, startTime,stopTime): bikes = m.get(citibike["bikes"], bike) initialDate = (datetime.datetime.strptime(startTime[0:19], '%Y-%m-%d %H:%M:%S')).date() finalTime = stopTime[11:16] initialTime = startTime[11:16] if bikes is None: datesHash = m.newMap(numelements=784, maptype="PROBING", loadfactor=0.5, comparefunction=compareStopIds) m.put(citibike["bikes"], bike, datesHash) if m.get(me.getValue(m.get(citibike["bikes"], bike)), initialDate) is None: datesHash = me.getValue(m.get(citibike["bikes"], bike)) bikes = {"routes":None, "useTime":0, "breakTime":0, "times": None} bikes["routes"] = lt.newList(datastructure="ARRAY_LIST", cmpfunction=compareroutes) bikes["times"]=st.newStack() m.put(datesHash,initialDate, bikes) datesHash = me.getValue(m.get(me.getValue(m.get(citibike["bikes"], bike)), initialDate)) if lt.size(datesHash["routes"]) == 0: lt.addLast(datesHash["routes"], origin) else: lt.addLast(datesHash["routes"], destination) breakTime = seeTime(st.top(datesHash["times"]),initialTime) datesHash["breakTime"]+=breakTime datesHash["useTime"]+=duration/60 st.push(datesHash["times"], finalTime)
def dfs(graph, search, v): """ DFS Args: search: La estructura de busqueda v: Vertice desde donde se relajan los pesos Returns: El grafo Raises: Exception """ try: map.put(search['marked'], v, True) map.put(search['onStack'], v, True) edges = g.adjacentEdges(graph, v) for edge in lt.iterator(edges): w = e.other(edge, v) if (not st.isEmpty(search['cycle'])): return search elif ((not map.get(search['marked'], w)['value'])): map.put(search['edgeTo'], w, edge) dfs(graph, search, w) elif (map.get(search['onStack'], w)['value']): f = edge while (e.either(f) != w): st.push(search['cycle'], f) f = map.get(search['edgeTo'], e.either(f))['value'] st.push(search['cycle'], f) return search map.put(search['onStack'], v, False) except Exception as exp: error.reraise(exp, 'cycle:dfs')
def pathTo(search, vertex): """ Retorna el camino entre source y vertex en una pila. Args: search: La estructura de busqueda vertex: El vertice de destino Returns: Una pila con el camino entre source y vertex Raises: Exception """ try: if hasPathTo(search, vertex) is False: return None path = stack.newStack() while vertex != search['source']: visited_v = map.get(search['visited'], vertex)['value'] edge = visited_v['edgeTo'] stack.push(path, edge) vertex = e.either(edge) return path except Exception as exp: error.reraise(exp, 'dks:pathto')
def pathTo(search, vertex): """ Retorna el camino entre el vertices source y el vertice vertex Args: search: La estructura con el recorrido vertex: Vertice de destingo Returns: Una pila con el camino entre el vertices source y el vertice vertex Raises: Exception """ try: if hasPathTo(search, vertex) is False: return None path = stack.newStack() while vertex != search['source']: stack.push(path, vertex) vertex = map.get(search['visited'], vertex)['value']['edgeTo'] stack.push(path, search['source']) return path except Exception as exp: error.reraise(exp, 'bfs:pathto')
def pathTowithLimiter(search, vertex, grafo, limit): """ Retorna el camino entre el vertices source y el vertice vertex Args: search: La estructura con el recorrido vertex: Vertice de destingo Returns: Una pila con el camino entre el vertices source y el vertice vertex Raises: Exception """ try: if hasPathTo(search, vertex) is False: return None path = stk.newStack() TIEMPO = 0 limit=limit*60 while vertex != search['source']: stk.push(path, vertex) papu=vertex vertex = map.get(search['visited'], vertex)['value']['edgeTo'] edge=graph.getEdge(grafo,vertex,papu) t=int(edge['weight'])+1200 TIEMPO+=t if TIEMPO>limit: return None stk.push(path, search['source']) return path,TIEMPO except Exception as exp: error.reraise(exp, 'dfs:pathtotuniao')
def dfsVertex(graph, search, vertex): """ Genera un recorrido DFS sobre el grafo graph Args: graph: El grafo a recorrer source: Vertice de inicio del recorrido. Returns: Una estructura para determinar los vertices conectados a source Raises: Exception """ try: queue.enqueue(search['pre'], vertex) map.put(search['marked'], vertex, True) lstadjacents = g.adjacents(graph, vertex) adjiterator = it.newIterator(lstadjacents) while it.hasNext(adjiterator): adjvert = it.next(adjiterator) if not map.contains(search['marked'], adjvert): dfsVertex(graph, search, adjvert, ) queue.enqueue(search['post'], vertex) stack.push(search['reversepost'], vertex) return search except Exception as exp: error.reraise(exp, 'dfo:dfsVertex')
def musicaParaEstudiar(catalog, minInstrumental, maxInstrumental, minTempo, maxTempo): mapa = catalog['RepsPor_instrumentalness'] Reproducciones_Rango_Instrumentalness = model.Reproducciones_Rango_Instrumentalness( mapa, minInstrumental, maxInstrumental) lista_pistas = model.Lista_unicas_Instrumentalness( Reproducciones_Rango_Instrumentalness) #Obtenemos la lista lista_pistas = mp.valueSet(lista_pistas) #Organizamos por tempo con mapa om_pistas_tempo = model.OM_pistas_tempo(lista_pistas) lista_resultado = model.PistasRangoTempo(om_pistas_tempo, minTempo, maxTempo) cantidad = 0 retornar = stk.newStack() for lista in lt.iterator(lista_resultado): cantidad = cantidad + lt.size(lista) aleatorios_1 = sample(range(1, lt.size(lista_resultado)), 5) for pos1 in aleatorios_1: lista = lt.getElement(lista_resultado, pos1) pos2 = randint(1, lt.size(lista)) elemento = lt.getElement(lista, pos2) stk.push(retornar, elemento) return cantidad, retornar
def NewDate(trip): CadaFecha = { "bicicleta": None, "Date": None, 'HoraInicio': None, 'HoraFin': None, "SegundosUsada": None, "SegundosParqueada": 0, "RecorridosRealizados": None } CadaFecha["Date"] = (datetime.datetime.strptime( (trip["starttime"][:19]), '%Y-%m-%d %H:%M:%S')).date() CadaFecha["bicicleta"] = trip["bikeid"] CadaFecha["HoraInicio"] = datetime.datetime.strptime( (trip["starttime"][:19]), '%Y-%m-%d %H:%M:%S') CadaFecha["HoraFin"] = datetime.datetime.strptime((trip["stoptime"][:19]), '%Y-%m-%d %H:%M:%S') Delta = CadaFecha["HoraFin"] - CadaFecha["HoraInicio"] SegundosPorViaje = (Delta.total_seconds()) CadaFecha["SegundosUsada"] = SegundosPorViaje CadaFecha["RecorridosRealizados"] = stack.newStack() stack.push(CadaFecha["RecorridosRealizados"], (trip["start station id"], trip["end station id"])) return CadaFecha
def dfs_extra(search, graph, vertex, components, path, cycles, weights): """ Funcion auxiliar para calcular un recorrido DFS Args: search: Estructura para almacenar el recorrido vertex: Vertice de inicio del recorrido. Returns: Una estructura para determinar los vertices conectados a source Raises: Exception """ try: if vertex is not None: stk.push(path, vertex) if vertex is not None: cycles[-1].append(vertex) adjlst = g.adjacents(graph, vertex) adjslstiter = it.newIterator(adjlst) while (it.hasNext(adjslstiter)): w = it.next(adjslstiter) if w is not None: visited = map.get(search['visited'], w) vertex_comp = map.get(components, vertex)['value'] w_comp = map.get(components, w)['value'] # if aun no he visitado todos mis hijos if visited is None and vertex_comp == w_comp: map.put(search['visited'], w, { 'marked': True, 'edgeTo': vertex }) edge = g.getEdge(graph, vertex, w)['weight'] current_weight = edge + 20 weights[-1] += current_weight dfs_extra(search, graph, w, components, path, cycles, weights) if g.outdegree(graph, vertex) > 1: new_arr = [] new_arr.append(path['last']['info']) dummy = path['first'] while dummy['next'] is not None: new_arr.append(dummy['info']) dummy = dummy['next'] if new_arr != cycles[-1]: cycles.append(new_arr) weights.append(weights[-1]) map.put(search['visited'], vertex, None) stk.pop(path) except Exception as exp: error.reraise(exp, 'dfs:dfsVertex')
def UpdateTimes(FechaExistente, trip): DeltaParquedo = abs((datetime.datetime.strptime( (trip["starttime"][:19]), '%Y-%m-%d %H:%M:%S')) - FechaExistente["HoraFin"]) SegundosParqueada = (DeltaParquedo.total_seconds()) FechaExistente["SegundosParqueada"] += SegundosParqueada FechaExistente["HoraInicio"] = datetime.datetime.strptime( (trip["starttime"][:19]), '%Y-%m-%d %H:%M:%S') FechaExistente["HoraFin"] = datetime.datetime.strptime( (trip["stoptime"][:19]), '%Y-%m-%d %H:%M:%S') Delta = FechaExistente["HoraFin"] - FechaExistente["HoraInicio"] SegundosPorViaje = (Delta.total_seconds()) FechaExistente["SegundosUsada"] += SegundosPorViaje stack.push(FechaExistente["RecorridosRealizados"], (trip["start station id"], trip["end station id"])) return FechaExistente
def musicaParaFestejar(catalog, minDance, maxDance, minEnergy, maxEnergy): #mapa ordenado : llaves= dance de la rep, valor: reproducciones con ese dance mapa_inicial = catalog['RepsPor_danceability'] #lista de todas las reproducciones cuyo dance está en el rango parametro|||| # ||||| por esto, de aqui en adelante todo está dentro del rango de Danceability #esto es una lista de las listas de reps por cada valor de danceability repsEn_Rango_danceability = model.repsPor_Rango_danceability( mapa_inicial, minDance, maxDance) #map/hashtable de PISTAS con id de pista/track_id como llaves, valor: artist_id, danceability, energy pistasEn_Rango_danceability = model.ListReps_to_HashPistasUnicas( repsEn_Rango_danceability) #se convierte a lista pistasEn_Rango_danceability = mp.valueSet(pistasEn_Rango_danceability) # se convierte a un mapa ordenado por Energy : llave=ValorEnergy, Valor=listadePistas con ese valor de energy Om_pistasEn_Rango_danceability = model.ListPistas_to_OMPistas_porEnergy( pistasEn_Rango_danceability) #se obtienen las que tienen el energy en el rango: lista_resultado = model.PistasPor_Rango_energy( Om_pistasEn_Rango_danceability, minEnergy, maxEnergy) cantidad = 0 retornar = stk.newStack() for pistasConEnergy in lt.iterator(lista_resultado): cantidad = cantidad + lt.size(pistasConEnergy) '''if stk.size(retornar) < 5 and : for track in lt.iterator(pistasConEnergy): if stk.size(retornar) < 5: stk.push(retornar, track)''' aleatorios_1 = sample(range(1, lt.size(lista_resultado)), 5) for pos1 in aleatorios_1: lista = lt.getElement(lista_resultado, pos1) pos2 = randint(1, lt.size(lista)) elemento = lt.getElement(lista, pos2) stk.push(retornar, elemento) return cantidad, retornar
def test_infoElements(): """ Este test busca confirmar que los datos se almacenen de forma correcta y que sean los valores correctos en el orden apropiado de la estructura. """ 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) elem = st.top(stack) assert (st.size(stack) == 10) assert (elem == book9) elem = st.pop(stack) assert (st.size(stack) == 9) assert (elem == book9) elem = st.pop(stack) assert (st.size(stack) == 8) assert (elem == book7) elem = st.top(stack) assert (st.size(stack) == 8) assert (elem == book4) st.push(stack, book9) assert (st.size(stack) == 9) elem = st.top(stack) assert (elem == book9)
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_pushElements(): """ Se prueba la creacion de una nueva pila, se agregan todos los datos creados por sistema y se imprime su valor """ stack = st.newStack(list_type) 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) iterator = it.newIterator(stack) while it.hasNext(iterator): element = it.next(iterator) print(element)
def test_push_pop(): """ Este test prueba que la cola pueda manejar inserciones y eliminaciones de forma correcta siguiendo un orden establecido, y que no quede referencia al objeto sacado despues de haberlo removido de la cola """ stack = st.newStack(list_type) assert (st.size(stack) == 0) assert (st.isEmpty(stack)) st.push(stack, book5) assert (st.size(stack) == 1) assert (st.top(stack) == st.pop(stack)) assert (st.size(stack) == 0) st.push(stack, book6) assert (st.size(stack) == 1) assert (st.top(stack) == st.pop(stack)) assert (st.size(stack) == 0) st.push(stack, book3) assert (st.size(stack) == 1) assert (st.top(stack) == st.pop(stack)) assert (st.size(stack) == 0) st.push(stack, book10) assert (st.size(stack) == 1) assert (st.top(stack) == st.pop(stack)) assert (st.size(stack) == 0) st.push(stack, book1) assert (st.size(stack) == 1) assert (st.top(stack) == st.pop(stack)) assert (st.size(stack) == 0) st.push(stack, book2) assert (st.size(stack) == 1) assert (st.top(stack) == st.pop(stack)) assert (st.size(stack) == 0) st.push(stack, book8) st.push(stack, book4) st.push(stack, book7) st.push(stack, book9) assert (st.size(stack) == 4) assert book9 == st.pop(stack) assert book7 == st.pop(stack) assert book4 == st.pop(stack) assert book8 == st.pop(stack) assert (st.size(stack) == 0)
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 ConsultaRutasCirculares(bikes, vertice, inferior, superior): ListaCompleta = ListaAdyacentes(bikes, vertice) lstiterator = it.newIterator(ListaCompleta) conteoCaminos = 0 stackfinal = stack.newStack() CadaRuta = queue.newQueue() ConteoDeRutas = 0 while it.hasNext(lstiterator): eachaStation = it.next(lstiterator) primerRecorrido = getEdge(bikes['grafo'], vertice, eachaStation) search = minimumCostPaths(bikes, eachaStation) colados = minimumCostPath(bikes, vertice) if colados and ((stack.size(colados)) * 60 * 20) < superior: pesoporestaciones = (stack.size(colados)) * 60 * 20 pesocamino = 0 pesoTOTALdos = pesoporestaciones + pesocamino + primerRecorrido[ 'weight'] CadaRuta = queue.newQueue() queue.enqueue(CadaRuta, primerRecorrido) while (not stack.isEmpty(colados)) and (pesoTOTALdos < superior): stopDOS = stack.pop(colados) pesoTOTALdos += stopDOS['weight'] queue.enqueue(CadaRuta, stopDOS) if inferior < pesoTOTALdos < superior and CadaRuta: CadaRuta["PesoPorRuta"] = pesoTOTALdos ConteoDeRutas += 1 stack.push(stackfinal, CadaRuta) return ConteoDeRutas, stackfinal #NO BORRAR LO COMENTADO ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ #NO BORRAR LO COMENTADO ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ #NO BORRAR LO COMENTADO ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ """ #Req 2 funcionando #Req 2 funcionando #Req 2 funcionando ListaCompleta = ListaAdyacentes(bikes, vertice) lstiterator=it.newIterator(ListaCompleta) conteoCaminos = 0 stackfinal = stack.newStack() while it.hasNext(lstiterator): eachaStation=it.next(lstiterator) primero = minimumCostPaths(bikes, vertice) primerpeso = distTo(primero, eachaStation) FirsPath = minimumCostPath(primero, eachaStation) Firststop = stack.pop(FirsPath) segundo = minimumCostPaths(bikes, eachaStation) SecondPath = minimumCostPath(bikes, vertice) if SecondPath: pesoconjunto = (distTo(segundo, vertice)) + primerpeso stack.push(SecondPath, Firststop) pathlen = stack.size(SecondPath) pesofinal = pesoconjunto + (pathlen*20*60) if inferior < pesofinal < superior: conteoCaminos += 1 SecondPath["PesoTotal"]=pesofinal stack.push(stackfinal, SecondPath) return conteoCaminos, stackfinal """ """
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 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 test_push_pop(stack, books): assert (st.size(stack) == 0) assert (st.isEmpty(stack)) st.push(stack, books[5]) assert (st.size(stack) == 1) assert (st.top(stack) == st.pop(stack)) assert (st.size(stack) == 0) st.push(stack, books[6]) assert (st.size(stack) == 1) assert (st.top(stack) == st.pop(stack)) assert (st.size(stack) == 0) st.push(stack, books[3]) assert (st.size(stack) == 1) assert (st.top(stack) == st.pop(stack)) assert (st.size(stack) == 0) st.push(stack, books[10]) assert (st.size(stack) == 1) assert (st.top(stack) == st.pop(stack)) assert (st.size(stack) == 0) st.push(stack, books[1]) assert (st.size(stack) == 1) assert (st.top(stack) == st.pop(stack)) assert (st.size(stack) == 0) st.push(stack, books[2]) assert (st.size(stack) == 1) assert (st.top(stack) == st.pop(stack)) assert (st.size(stack) == 0) st.push(stack, books[8]) st.push(stack, books[4]) st.push(stack, books[7]) st.push(stack, books[9]) assert (st.size(stack) == 4) assert books[9] == st.pop(stack) assert books[7] == st.pop(stack) assert books[4] == st.pop(stack) assert books[8] == st.pop(stack) assert (st.size(stack) == 0)
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))