def plotMinimumCostPathMap(analyzer, vertexa, vertexb): """ Crea un mapa interactivo de la ruta de costo mínimo entre dos puntos de conexión """ lstvertexs = controller.getMinimumCostPathVertexs(analyzer, vertexb) lstcoordinates = controller.getPathCoordinates(analyzer, lstvertexs) origincoords = lt.firstElement(lstcoordinates) destcoords = lt.lastElement(lstcoordinates) originpos = lt.isPresent(lstcoordinates, origincoords) destpos = lt.isPresent(lstcoordinates, destcoords) lt.removeFirst(lstcoordinates) lt.removeLast(lstcoordinates) map = folium.Map(origincoords, zoom_start=2.5) for location in lt.iterator(lstcoordinates): folium.Marker(location).add_to(map) lt.insertElement(lstcoordinates, origincoords, originpos) lt.insertElement(lstcoordinates, destcoords, destpos) folium.Marker(origincoords, str(vertexa.replace('-', ', ')), icon=folium.Icon(icon='flag', color='red')).add_to(map) folium.Marker(destcoords, str(vertexb.replace('-', ', ')), icon=folium.Icon(icon='flag', color='red')).add_to(map) folium.PolyLine(lstcoordinates['elements'], color="grey", weight=2.5, opacity=0.75).add_to(map) map.save("map3.html")
def resistencia(graph, tiempo, estacion_inicio): rutas = lt.newList(comparar_data) borrar = lt.newList(comparar_data) estaciones = adj.adjacents(graph['grafo'], estacion_inicio) ite = it.newIterator(estaciones) no_repetir = m.newMap(numelements=17, prime=109345121, maptype='CHAINING', loadfactor=0.5, comparefunction=comparar_data) m.put(no_repetir, estacion_inicio, 1) while (it.hasNext(ite)): est = it.next(ite) edg = adj.getEdge(graph['grafo'], estacion_inicio, est) duracion = edg["weight"] if duracion < (tiempo * 60) and m.contains(no_repetir, est) == False: ruta = {} ruta["Estacion_final"] = est ruta["Estacion_inicio"] = estacion_inicio ruta["tiempo"] = duracion lt.addLast(rutas, ruta) lt.addLast(borrar, ruta) m.put(no_repetir, est, 1) ite2 = it.newIterator(borrar) while (it.hasNext(ite2)): est2 = it.next(ite2) estaciones2 = adj.adjacents(graph['grafo'], est2["Estacion_final"]) ite3 = it.newIterator(estaciones2) while (it.hasNext(ite3)): est3 = it.next(ite3) edg2 = adj.getEdge(graph['grafo'], est2["Estacion_final"], est3) if m.contains(no_repetir, est3) == False: if "Tiempo_acumulado" not in est2.keys(): tiempo_acumulado = edg2["weight"] + est2["tiempo"] if tiempo_acumulado < (tiempo * 60): ruta = {} ruta["Estacion_final"] = est3 ruta["Estacion_inicio"] = est2["Estacion_final"] ruta["tiempo"] = edg2["weight"] ruta["tiempo_acumulado"] = tiempo_acumulado lt.addLast(rutas, ruta) lt.addLast(borrar, ruta) m.put(no_repetir, est3, 1) else: tiempo_acumulado = edg2["weight"] + est2["tiempo_acumulado"] if tiempo_acumulado < (tiempo * 60): ruta = {} ruta["Estacion_final"] = est3 ruta["Estacion_inicio"] = est2["Estacion_final"] ruta["tiempo"] = edg2["weight"] ruta["tiempo_acumulado"] = tiempo_acumulado lt.addLast(rutas, ruta) lt.addLast(borrar, ruta) m.put(no_repetir, est3, 1) lt.removeFirst(borrar) return rutas
def if_add_video_req(video, top, k: int, n: int): min_top = None if not lt.isEmpty(top): min_top = lt.firstElement(top) if not min_top: lt.addFirst(top, video) # ... or likesVideo > likesMinTop: elif lt.size(top) < n or lt.getElement(video[0], k) > lt.getElement( min_top[0], k): add_to_top(video, top, k) if lt.size(top) > n: lt.removeFirst(top)
def estacionesCriticas(dataBase) -> dict: top3In = list.newList() top3Out = list.newList() bot3 = list.newList() analysis = Analysis.topViajes(dataBase) i = 0 while i < 3: list.addLast(top3In, list.removeFirst(analysis[0])) list.addLast(top3Out, list.removeFirst(analysis[1])) list.addFirst(bot3, list.removeLast(analysis[2])) i += 1 del analysis return (top3In, top3Out, bot3)
def getBestTime(database: DataBase, area1: str, area2: str, time1, time2) -> dict: route = database.getRoute(area1, area2).getRoute() route = orderedmap.values(route, time1, time2) sort.mergesort(route, cmp.trip) trip = list.removeFirst(route) return (trip.seconds, trip.time)
def ejecutarSeverityByTime(dataBase)->None: timeLo = input("\nIngrese la hora inicial ('HH:MM:SS'): ") timeHi = input("\nIngrese la hora final ('HH:MM:SS'): ") print(f"\nBuscando accidentes entre las {timeLo} y las {timeHi} ....") print("Los resultados son:") data = controller.getSeverityByTime(dataBase,timeLo, timeHi) count = len(data) total = lt.removeFirst(data) while count > 0: count -= 1 result = lt.removeFirst(data) if result is not None: print(f"\tDe severidad {result[0]} se encontraron {result[1]} accidentes") print(f"con un total de {total} accidentes")
def criticalStations(citibike): """ RETO 4 | REQ 3 Retorna: Las tres estaciones de donde salen más viajes. La tres estaciones de donde llegan más viajes. La tres estaciones menos usadas. """ top_arrival = [] top_departure = [] least_used = [] arrival_lt_sorted = lt.newList(datastructure='ARRAY_LIST', cmpfunction=compareValues) departure_lt_sorted = lt.newList(datastructure='ARRAY_LIST', cmpfunction=compareValues) total_trips_sorted = lt.newList(datastructure='ARRAY_LIST', cmpfunction=compareValues) stations_keys = m.keySet(citibike['Edges_Map']) iterator = it.newIterator(stations_keys) while it.hasNext(iterator): station = it.next(iterator) sta = m.get(citibike['Edges_Map'], station) lt.addLast(arrival_lt_sorted, sta) lt.addLast(departure_lt_sorted, sta) lt.addLast(total_trips_sorted, sta) mg.mergesort(arrival_lt_sorted, greaterValueArrival) mg.mergesort(departure_lt_sorted, greaterValueDeparture) mg.mergesort(total_trips_sorted, greaterTotalTrips) i = 0 while i < 3: top_arr = lt.removeFirst(arrival_lt_sorted) top_arrival.append(top_arr) top_dep = lt.removeFirst(departure_lt_sorted) top_departure.append(top_dep) least = lt.removeLast(total_trips_sorted) least_used.append(least) i += 1 return top_arrival, top_departure, least_used
def mvpDia(database, date, n): date = Date.newDate(date) wallets = Analysis.getPoints(database, date) values = [] while (n > len(values)) and (not lt.isEmpty(wallets)): wallet = lt.removeFirst(wallets) values.append((wallet.id, wallet.points)) return values
def req2(analyzer,key): entry=mp.get(analyzer['interconnections'],key) lista=me.getValue(entry) numero=lt.removeFirst(lista) if numero > 1: entry1=mp.get(analyzer['name_landing_id_hash'],key) lt.addFirst(lista,numero) return me.getValue(entry1)+'. ID: '+key+'. Total de cables conectados: '+str(numero)
def ejecutarSeverityByDate(dataBase)->None: initialDate = input("\nIngrese la fecha (YYYY-MM-DD): ") print("\nBuscando accidentes de " + initialDate + "....") print("Los resultados son:") data = controller.getSeverityByDate(dataBase,initialDate) count = len(data) total = lt.removeFirst(data) while count > 0: count -= 1 result = lt.removeFirst(data) if result is not None: if result[0] != 'max': print(f"\tDe severidad {result[0]} se encontraron {result[1]} accidentes") else: max = result[1] print(f"con un total de {total} accidentes")
def mvpRango(database, date1, date2, m): date1 = Date.newDate(date1) date2 = Date.newDate(date2) wallets = Analysis.getPointsV2(database, date1, date2) values = [] while (m > len(values)) and (not lt.isEmpty(wallets)): wallet = lt.removeFirst(wallets) values.append((wallet['id'], wallet['points'])) return values
def parteA_services(DataBase, N): comp = DataBase.getCompanies() values = map.valueSet(comp) sort.mergesort(values, Comparation.compareServices) respuesta = [] while (N > len(respuesta)) and (not lt.isEmpty(values)): company = lt.removeFirst(values) respuesta.append((company.name, company.services)) return respuesta
def add_lat_lo(citibike, trip): mapa = citibike["mapa_lat_lon"] estacion_inicio = trip["start station id"] latitud_inicio = trip["start station latitude"] longitud_inicio = trip["start station longitude"] llave = latitud_inicio + "," + longitud_inicio estacion_final = trip["end station id"] latitud_final = trip["end station latitude"] longitud_final = trip["end station longitude"] llavev2 = latitud_final + "," + longitud_final existe = m.get(mapa, "todos") if existe is None: lista_owo = lt.newList("ARRAY_LIST") a_ver = [] if llave not in a_ver: a_ver.append(llave) if llavev2 not in a_ver: a_ver.append(llavev2) lt.addLast(lista_owo, a_ver) for i in a_ver: lt.addLast(lista_owo, i) m.put(mapa, "todos", lista_owo) else: existe = me.getValue(existe) lista = lt.getElement(existe, 1) lt.removeFirst(existe) no_estan = [] if llave not in lista: lista.append(llave) no_estan.append(llave) if llavev2 not in lista: lista.append(llavev2) no_estan.append(llavev2) lt.addFirst(existe, lista) for i in no_estan: lt.addLast(existe, i) EXadd_lat_lon(mapa, llave, estacion_inicio) EXadd_lat_lon(mapa, llavev2, estacion_final)
def buscar_estaciones_peor_top(graph, reference_table): """"Funcion para hallar los viajes que llegan a una estacion!""" estaciones = lt.newList() vertices = gr.vertices(graph) it_vertice = it.newIterator(vertices) while it.hasNext(it_vertice): vert = it.next(it_vertice) estacion = gr.indegree(graph, vert) estacion += gr.outdegree(graph, vert) lt.addLast(estaciones, (estacion, vert)) merge.mergesort(estaciones, lessFunction) final_top = [] for i in range(3): top = lt.firstElement(estaciones) nombre = conversor_id_nombre(top[1], reference_table, "end station name") final_top.append((top[0], nombre)) lt.removeFirst(estaciones) return final_top
def getTimeSeverity (timeLo, timeHi, dataBase): severityMap = newSeverity() index = om.valueSet(dataBase['dateIndex']) total = 0 entry1 = lt.size(index) while entry1 > 0: entry1 -= 1 dateEntry = lt.removeFirst(index) dateKeys = m.keySet(dateEntry['severityIndex']) entry2 = lt.size(dateKeys) while entry2 > 0: entry2 -= 1 severityKey = lt.removeFirst(dateKeys) severityEntry = m.get(dateEntry['severityIndex'],severityKey) severityEntry = me.getValue(severityEntry) severityEntry = om.values(severityEntry['timeIndex'],timeLo,timeHi) entry3 = lt.size(severityEntry) while entry3 > 0: entry3 -= 1 timeEntry = lt.removeFirst(severityEntry) timeEntry = timeEntry['size'] total += timeEntry resultVal = m.contains(severityMap['severityIndex'],severityKey) if resultVal: preValue = m.get(severityMap['severityIndex'],severityKey) preValue = me.getValue(preValue) m.put(severityMap['severityIndex'],severityKey, preValue + timeEntry) else: m.put(severityMap['severityIndex'],severityKey,timeEntry) severityMap['size'] = total return severityMap
def getDataSeverity (index): severityMap = newSeverity() entry1 = lt.size(index) while entry1 > 0: entry1 -= 1 dateEntry = lt.removeFirst(index) date = me.getKey(dateEntry) dateEntry = me.getValue(dateEntry) dateKeys = m.keySet(dateEntry['severityIndex']) severityMap['size'] += dateEntry['size'] if m.contains(severityMap['severityIndex'],'max'): if m.get(severityMap['severityIndex'],'max') < dateEntry['size']: m.put(severityMap['severityIndex'],'max', dateEntry['size']) else: m.put(severityMap['severityIndex'],'max', date) entry2 = lt.size(dateKeys) while entry2 > 0: entry2 -= 1 severityKey = lt.removeFirst(dateKeys) if severityKey is not None: severityEntry = m.get(dateEntry['severityIndex'],severityKey) severityEntry = me.getValue(severityEntry) resultVal = m.contains(severityMap['severityIndex'],severityKey) if resultVal: preValue = m.get(severityMap['severityIndex'],severityKey) preValue = me.getValue(preValue) m.put(severityMap['severityIndex'],severityKey, preValue + severityEntry['size']) else: m.put(severityMap['severityIndex'],severityKey,severityEntry['size']) return severityMap
def dequeue(queue): """ Retorna el elemento en la primer posición de la cola, y lo elimina. Args: queue: La cola donde se eliminará el elemento Returns: El primer elemento de la cola Raises: Exception """ try: return lt.removeFirst(queue) except Exception as exp: error.reraise(exp, 'TADQueue->dequeue: ')
def pop(stack): """ Retorna el elemento presente en el tope de la pila. Args: stack: La pila de donde se retirara el elemento Returns: El elemento del tope de la pila Raises: Exception """ try: return lt.removeFirst(stack) except Exception as exp: error.reraise(exp, 'TADStack->pop: ')
def addInterconnection(analyzer,connection): if not mp.contains(analyzer['interconnections'], connection['origin']): lista=lt.newList('ARRAY_LIST') lt.addLast(lista,1) lt.addLast(lista,connection['cable_id']) mp.put(analyzer['interconnections'],connection['origin'],lista) elif mp.contains(analyzer['interconnections'], connection['origin']): entry=mp.get(analyzer['interconnections'],connection['origin']) lista=me.getValue(entry) esta=False for i in lt.iterator(lista): if i==connection['cable_id']: esta=True if not esta: numero=lt.removeFirst(lista) numero+=1 lt.addFirst(lista,numero)
def getSeverityByPreDate(dataBase, initialDate): initialDate = datetime.datetime.strptime(initialDate, '%Y-%m-%d') data = model.getSeverityByPreDate(dataBase, initialDate.date()) index = m.keySet(data['severityIndex']) count = lt.size(index) result = lt.newList() lt.addLast(result, data['size']) while count > 0: count -= 1 key = lt.removeFirst(index) if key is not None: num = m.get(data['severityIndex'], key) num = me.getValue(num) lt.addLast(result, (key, num)) return result
def getSeverityByTime(dataBase, timeLo, timeHi): timeLo = datetime.datetime.strptime(timeLo, '%H:%M:%S').time() timeHi = datetime.datetime.strptime(timeHi, '%H:%M:%S').time() print(timeLo) data = model.getSeverityByTime(dataBase, timeLo, timeHi) index = m.keySet(data['severityIndex']) count = lt.size(index) result = lt.newList() lt.addLast(result, data['size']) while count > 0: count -= 1 key = lt.removeFirst(index) if key is not None: num = m.get(data['severityIndex'], key) num = me.getValue(num) lt.addLast(result, (key, num)) return result
def test_removeFirst_array(altbooks, books): assert lt.size(altbooks) == 5 lt.removeFirst(altbooks) assert lt.size(altbooks) == 4 book = lt.getElement(altbooks, 1) assert book == books[1]
def stationsbyres(citibike,idstation,time_max): tiempo = minToseconds(time_max) lista = lt.newList('ARRAY_LIST',compareLists) recorrido = dfs.DepthFirstSearch(citibike['graph'],idstation) #Recorrido por el gráfo con DFS llaves = m.keySet(recorrido['visited']) #Extracción llaves del recorrido iterador = it.newIterator(llaves) #Inicializar Iterador con las llaves while it.hasNext(iterador): id = it.next(iterador) path = dfs.pathTo(recorrido,id) #Encontrar el "path" entre el vertice y el de destino if path is not None: n_lista=lt.newList('ARRAY_LIST') nueva_lista = lt.newList('ARRAY_LIST') while (not stack.isEmpty(path)): ruta = stack.pop(path) #Como path es pila, retornar el tope de la fila lt.addLast(n_lista,ruta) #Agregar a n_lista, la ruta suma = 0 while lt.size(n_lista)> 1 : if suma<= tiempo: german = lt.getElement(n_lista,1) #Hallar vértice 1 hola = lt.getElement(n_lista,2) #Hallar vértice 2 arco = gr.getEdge(citibike['graph'],german,hola) #ENcontrar el arco entre 1 y 2 peso = arco['weight'] #Encontar el peso del arco suma += peso #Suma de los pesos c= lt.removeFirst(n_lista) #Extraigo el primero de la lista lt.addLast(nueva_lista,c) #Lo añado a nueva_lista else: break if lt.isPresent(lista,nueva_lista) == 0: #Si no esta presente nueva lista en lista, lo agregó if lt.size(nueva_lista)<= 1: pass else: lt.addLast(lista,nueva_lista) else: pass count = 1 for a in range(1,lt.size(lista)+1): l = lt.getElement(lista,a) #Accedo a las listas dentro de la lista grande if lt.size(l)==2: print("=========================================") print(bold + "RUTA NÚMERO: "+ end + str(count)) print("\n") verticea = lt.getElement(l,1) verticeb = lt.getElement(l,2) arco = gr.getEdge(citibike['graph'],verticea, verticeb)['weight'] #Encuentro el peso entre dos vertices changeInfo(citibike,l,1) changeInfo(citibike,l,2) print(bold + "Segmento de ruta: " + end) printListContent(l) #Imprime los segmentos de las rutas con la información de "l" print(bold + "Tiempo estimado del segmento: "+ end) convertSecondsToDate(arco) #Convierte los segundos a formato fecha print("\n") count+=1 else: print("=========================================") print(bold + "RUTA NÚMERO: " + end + str(count)) print("\n") while 1 < lt.size(l): ll = lt.newList('ARRAY_LIST') vertice1 = lt.getElement(l,1) vertice2 = lt.getElement(l,2) arco = gr.getEdge(citibike['graph'],vertice1, vertice2)['weight'] #Encuentro el peso entre dos verices lt.addLast(ll,vertice1) lt.addLast(ll,vertice2) changeInfo(citibike,ll,1) changeInfo(citibike,ll,2) print(bold + "Segmento ruta: " + end) printListContent(ll) print(bold + "Tiempo estimado del segmento: "+ end) convertSecondsToDate(arco) #Convierte los segundos a formato fecha print("\n") lt.removeFirst(l) count+=1 print("-------------------------------------------------------") print(bold + "TOTAL DE RUTAS ENCONTRADAS: " + end +str(count-1)) return None
pass catalog = initCatalog(Tipo) loadData(catalog) print('Videos cargados: ' + str(lt.size(catalog['videos']))) videos = (catalog['videos']) print1stelement(videos, int(input2)) categoryID = catalog['category-id'] printcategoriesList(categoryID) elif int(inputs[0]) == 2: pais = input("Ingrese el pais por el que quiere filtrar \n") categoria = input("Ingrese la categoria por la que quiere filtrar \n") lista_filtrada = controller.filtrarvideos(catalog, pais, categoria) lista_filtrada_ordenada = controller.sortVideos(lista_filtrada) n = int(input('Numero de videos que quiere listar: ')) for i in range(0, n): print('* * *') print1stelement(lista_filtrada_ordenada, tipo=1) lt.removeFirst(lista_filtrada_ordenada) elif int(inputs[0]) == 3: pass elif int(inputs[0]) == 4: pass elif int(inputs[0]) == 5: pass else: sys.exit(0) sys.exit(0)