コード例 #1
0
def CompaniesInfo(catalog, criteria1, criteria2):
    """
    Proyecto Final | Req 1
    Retorna:
        Número total de taxis reportados.
        Número total de compañías.
        TOP X compañías con más taxis afiliados.
        TOP Y compañías con más servicios prestados.
    """
    companies_lt = m.keySet(catalog['Companies_Map'])
    num_companies = lt.size(companies_lt)

    moreCabs = lt.newList(datastructure='ARRAY_LIST', cmpfunction=None)
    moreServices = lt.newList(datastructure='ARRAY_LIST', cmpfunction=None)

    iterator = it.newIterator(companies_lt)
    while it.hasNext(iterator):
        company_name = it.next(iterator)
        company = m.get(catalog['Companies_Map'], company_name)

        lt.addLast(moreCabs, company)
        lt.addLast(moreServices, company)

    mg.mergesort(moreCabs, greaterNumCabs)
    mg.mergesort(moreServices, greaterNumServices)

    TOPNumCabs = lt.subList(moreCabs, 1, criteria1)
    TOPNumServices = lt.subList(moreServices, 1, criteria2)

    return catalog['Num_Total_Cabs'], num_companies, TOPNumCabs, TOPNumServices
コード例 #2
0
def reportegeneral(analyzer, parametrom, parametron):
    listaviajes = analyzer["lista"]
    lista = []
    companias = []
    for i in range(lt.size(listaviajes) + 1):
        taxiid = lt.getElement(listaviajes, i)["taxi_id"]
        compania = lt.getElement(listaviajes, i)["company"]
        if compania == "":
            compania = "independent owner"
        if compania not in companias:
            companias.append(compania)

        if taxiid not in lista:
            lista.append(taxiid)

        addCompany(analyzer, compania, taxiid, lt.getElement(listaviajes, i))
        addtaxid(analyzer, taxiid)
    rankingm = lt.newList("ARRAY_LIST")
    rankingn = lt.newList("ARRAY_LIST")
    for i in companias:
        compania = m.get(analyzer["mapcompany"], i)
        lt.addLast(rankingm, compania)
        lt.addLast(rankingn, compania)
    mg.mergesort(rankingm, greater_company)
    mg.mergesort(rankingn, greater_company_taxis)

    rankingm = lt.subList(rankingm, 1, parametrom + 1)
    rankingn = lt.subList(rankingn, 1, parametron + 1)
    return len(lista), len(companias), rankingm, rankingn
コード例 #3
0
def consulta2(Inite, fecha_ini, fecha_fin, top2):
    fecha_fin = transformador_fecha(fecha_fin)
    fecha_ini = transformador_fecha(fecha_ini)
    datos_entre_medio = om.values(Inite["mapa_fecha"], fecha_ini, fecha_fin)

    mapa_intermedio = m.newMap(maptype="PROBING",
                               comparefunction=compareStationsv2)
    for i in range(1, lt.size(datos_entre_medio) + 1):
        lista = lt.getElement(datos_entre_medio, i)
        lista = m.valueSet(lista)

        for e in range(1, lt.size(lista) + 1):
            elemento = lt.getElement(lista, e)
            existe = m.get(mapa_intermedio, elemento["taxi"])
            if existe is None:
                m.put(mapa_intermedio, elemento["taxi"], elemento)
            else:
                nodo_new = incrementalV3(me.getValue(existe), elemento)
                m.put(mapa_intermedio, nodo_new["taxi"], nodo_new)

    top_2 = lt.newList("ARRAY_LIST")
    mapa_intermedio_ordenado = m.valueSet(mapa_intermedio)
    mergesort.mergesort(mapa_intermedio_ordenado,
                        comparador_ascendente)  # SHELLSORT

    for i in range(1, lt.size(mapa_intermedio_ordenado) + 1):
        elemento = lt.getElement(mapa_intermedio_ordenado, i)
        lt.addLast(top_2, elemento)
        if i == top2:
            break

    return top_2
コード例 #4
0
def recomendarRutas(analyzer, agerange):
    ageGraph = crearGrafoEdad(analyzer, agerange)
    mayorsalida = majorStart(ageGraph["grafo"])
    mayordestino = majorDestiny(ageGraph["grafo"])
    if mayorsalida == None or mayordestino == None:
        return "No existen rutas para este rango de edad"
    else:
        pesos = lt.newList(datastructure="ARRAY_LIST")
        pathiterator = it.newIterator(ageGraph["lista"])
        while it.hasNext(pathiterator):
            viaje = it.next(pathiterator)
            if viaje["start station id"] == mayorsalida and viaje["end station id"] == mayordestino:
                lt.addLast(pesos, viaje["tripduration"])
        if lt.isEmpty(pesos):
            econ = None
        else:
            mrg.mergesort(pesos, lessfunction)
            econ = lt.firstElement(pesos)
        sal = m.get(analyzer["nameIndex"], mayorsalida)
        salnombre = me.getValue(sal)
        dest = m.get(analyzer["nameIndex"], mayordestino)
        destnombre = me.getValue(dest)
        W = {"salida":salnombre,
             "destino":destnombre,
             "tiempo":econ}
        return W
コード例 #5
0
def Req1RepInfo(chicagoAnalyzer, mTop, nTop):
    if 0 in {mTop, nTop}: return 0

    totalTaxi = m.size(chicagoAnalyzer['taxi'])
    totalCompany = m.size(chicagoAnalyzer['company'])
    topMCompanyTaxi = lt.newList(datastructure='ARRAY_LIST')
    topNCompanyService = lt.newList(datastructure='ARRAY_LIST')

    #Obtener taxis por compania
    ltCompany = m.keySet(chicagoAnalyzer['company'])
    for company in range(lt.size(ltCompany)):
        size = m.get(chicagoAnalyzer['company'],
                     lt.getElement(ltCompany, company))['value']
        lt.addLast(topMCompanyTaxi,
                   (lt.getElement(ltCompany, company), lt.size(size)))
        count = 0
        for idTaxi in range(lt.size(size)):
            infoT = m.get(chicagoAnalyzer['taxi'],
                          lt.getElement(size, idTaxi))['value']
            count += m.get(infoT, 'numServices')['value']
        lt.addLast(topNCompanyService,
                   (lt.getElement(ltCompany, company), count))

    ms.mergesort(topMCompanyTaxi, comparePoints)
    ms.mergesort(topNCompanyService, comparePoints)

    return totalTaxi, totalCompany, lt.subList(topMCompanyTaxi, 1,
                                               mTop)['elements'], lt.subList(
                                                   topNCompanyService, 1,
                                                   nTop)['elements']
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)
コード例 #7
0
def req1_return(Inite, ranking1, ranking2):
    companies_orden = m.valueSet(Inite["mapa_companies"])
    services_orden = m.valueSet(Inite["mapa_companies"])

    mergesort.mergesort(services_orden,
                        comparador_ascendente_services)  # SHELLSORT
    mergesort.mergesort(companies_orden,
                        comparador_ascendente_taxis)  # SHELLSORT
    cantidad_compañias_taxi = m.size(Inite["mapa_companies"])
    top1 = lt.newList("ARRAY_LIST")
    top2 = lt.newList("ARRAY_LIST")
    for i in range(1, lt.size(companies_orden) + 1):
        elemento = lt.getElement(companies_orden, i)
        lt.addLast(top1, elemento)
        if i == ranking1:
            break
    for i in range(1, lt.size(services_orden) + 1):
        elemento = lt.getElement(services_orden, i)
        lt.addLast(top2, elemento)
        if i == ranking2:
            break
    return {
        "ranking1": top1,
        "ranking2": top2,
        "compañias taxi": cantidad_compañias_taxi,
        "total taxis": len(Inite["Taxis sin repetir"]),
    }
コード例 #8
0
def parteA_consulta(inicial, rankingM, rankingN):
    orden_compañias = m.valueSet(inicial["compañias"])
    compañias_servicios_ordenados = m.valueSet(inicial["compañias"])

    mergesort.mergesort(orden_compañias, comparador_de_taxis)
    mergesort.mergesort(compañias_servicios_ordenados, comparador_de_servicios)

    numero_compañias = m.size(inicial["compañias"])

    topM = lt.newList("ARRAY_LIST")
    topN = lt.newList("ARRAY_LIST")

    cuantas_tengoM = 1
    while cuantas_tengoM <= rankingM:
        elemento_agregar = lt.getElement(orden_compañias, cuantas_tengoM)
        lt.addLast(topM, elemento_agregar)
        cuantas_tengoM += 1

    cuantas_tengoN = 1
    while cuantas_tengoN <= rankingN:
        elemento_agregar = lt.getElement(compañias_servicios_ordenados,
                                         cuantas_tengoN)
        lt.addLast(topN, elemento_agregar)
        cuantas_tengoN += 1

    return (topM, topN, numero_compañias, len(inicial["taxis"]))
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
コード例 #10
0
def criticStations(citibike):
    """
    Top 3 Llegada, Top 3 Salida y Top 3 menos usadas
    Req 3
    """
    #Listas respuesta
    topLlegada = lt.newList(datastructure='ARRAY_LIST',
                            cmpfunction=compareroutes)
    topSalida = lt.newList(datastructure='ARRAY_LIST',
                           cmpfunction=compareroutes)
    intopUsadas = lt.newList(datastructure='ARRAY_LIST',
                             cmpfunction=compareroutes)

    #Listas temporales para obtener el top 3
    top3LS = lt.newList(datastructure='ARRAY_LIST', cmpfunction=compareroutes)
    inTop3 = lt.newList(datastructure='ARRAY_LIST', cmpfunction=compareroutes)

    tempLT = lt.newList(cmpfunction=compareroutes)
    ltKeys = gr.edges(citibike['connections'])
    for arc in range(1, lt.size(ltKeys) + 1):
        lt.addLast(tempLT, lt.getElement(ltKeys, arc)['count'])

    ms.mergesort(tempLT, greatequal)

    for i in range(1, 10):
        lt.addLast(top3LS, lt.getElement(tempLT, i))
    for i in range(3):
        lt.addLast(inTop3, lt.getElement(tempLT, lt.size(tempLT) - i))

    vxl = 1
    while vxl <= lt.size(tempLT) and lt.size(topLlegada) <= 3:
        if lt.isPresent(top3LS, lt.getElement(ltKeys, vxl)['count']):
            vxA = getStation(citibike,
                             lt.getElement(ltKeys, vxl)['vertexA'])[1]
            if not lt.isPresent(topLlegada, vxA):
                lt.addLast(topLlegada, vxA)
        vxl += 1

    vxs = 1
    while vxs <= lt.size(tempLT) and lt.size(topSalida) <= 3:
        if lt.isPresent(top3LS, lt.getElement(ltKeys, vxs)['count']):
            vxB = getStation(citibike,
                             lt.getElement(ltKeys, vxs)['vertexB'])[1]
            if not lt.isPresent(topLlegada, vxB):
                lt.addLast(topSalida, vxB)
        vxs += 1

    vxin = 1
    while vxin <= lt.size(tempLT) and lt.size(intopUsadas) <= 3:
        if lt.isPresent(inTop3, lt.getElement(ltKeys, vxin)['count']):
            vxA = getStation(citibike,
                             lt.getElement(ltKeys, vxin)['vertexA'])[1]
            if not lt.isPresent(intopUsadas, vxA):
                lt.addLast(intopUsadas, vxA)
        vxin += 1

    return topLlegada, topSalida, intopUsadas
コード例 #11
0
def top_servcios(catalogo):
    llaves=m.keySet(catalogo["lista_compañias"])
    ite=it.newIterator(llaves)
    lista=lt.newList(datastructure='SINGLE_LINKED', cmpfunction=None)
    while it.hasNext(ite):
        llave=it.next(ite)
        pareja=m.get(catalogo["lista_compañias"],llave)
        lt.addLast(lista,pareja)
    mer.mergesort(lista,comparar_data_servicios)
    return lista
コード例 #12
0
def DiciaLista(PuntosR):
    ListaStr = lt.newList("ARRAY_LIST")
    ListaL = m.keySet(PuntosR)
    for i in range(1 + lt.size(ListaL)):
        Llave = lt.getElement(ListaL, i)
        Valor = m.get(PuntosR, Llave)
        Valor = Valor["value"]
        Str = str(Llave) + str("_: ") + str(Valor)
        lt.addLast(ListaStr, Str)
    mg.mergesort(ListaStr, GreaterTaxis)
    return ListaStr
コード例 #13
0
def topTarget(dataBase: dict, target: int) -> list:
    targetGraph = dataBase['target']

    targetList = list.newList()

    if map.contains(targetGraph, target):
        targetGraph = map.get(targetGraph, target)
        targetGraph = mapentry.getValue(targetGraph)
        targetList = graph.edges(targetGraph)
        mergesort.mergesort(targetList, Comparation.targetVal)

    return targetList
コード例 #14
0
def parteA4(analyzer):
    lista = lt.newList()
    companies = m.keySet(analyzer['companyByTrips'])
    iterator = it.newIterator(companies)
    while it.hasNext(iterator):
        company = it.next(iterator)
        value = m.get(analyzer['companyByTrips'], company)['value']
        size = m.size(value)
        data = {'key': company, 'value': size}
        lt.addLast(lista, data)
    ms.mergesort(lista, compareTripsValues)
    return lista
コード例 #15
0
def consulta_parteBA(inicial, fecha, top):
    fecha = datetime.datetime.strptime(fecha, "%Y-%m-%d")
    fecha = fecha.date()
    mapa_taxi = me.getValue(om.get(inicial["fechas"], fecha))
    final = lt.newList("ARRAY_LIST")
    lst = m.valueSet(mapa_taxi)
    mergesort.mergesort(lst, comparador_puntos)
    cuantas_tengo = 1
    while cuantas_tengo <= top:
        elemento_agregar = lt.getElement(lst, cuantas_tengo)
        lt.addLast(final, elemento_agregar)
        cuantas_tengo += 1
    return final
コード例 #16
0
def consulta_puntos_PROV(Inite, fecha, top):

    fecha = transformador_fecha(fecha)
    mapa = me.getValue(om.get(Inite["mapa_fecha"], fecha))
    top_final = lt.newList("ARRAY_LIST")
    lista_ordenada = m.valueSet(mapa)
    mergesort.mergesort(lista_ordenada, comparador_ascendente)  # SHELLSORT
    for i in range(1, lt.size(lista_ordenada) + 1):
        a_ver = lt.getElement(lista_ordenada, i)
        lt.addLast(top_final, a_ver)
        if i == top:
            break
    return top_final
コード例 #17
0
def getToStationFromCoordinates(citibike, Lat1, Lon1, Lat2, Lon2):
    """
    RETO4 | REQ 6
    Dada una latitud y longitud inicial,
    se halla la estación de Citibike más cercana.

    Dada una coordenada de destino, se halla
    la estación de Citibike más cercana.

    Se calcula la ruta de menor tiempo entre estas 
    dos estaciones.
    """

    stations_keys = m.keySet(citibike['Edges_Map'])
    initialStationSortedByDistance = lt.newList(datastructure='ARRAY_LIST',
                                                cmpfunction=compareValues)
    finalStationSortedByDistance = lt.newList(datastructure='ARRAY_LIST',
                                              cmpfunction=compareValues)

    iterator = it.newIterator(stations_keys)
    while it.hasNext(iterator):
        station = it.next(iterator)
        sta = m.get(citibike['Edges_Map'], station)

        staLat = float(sta['value']['Latitude'])
        staLon = float(sta['value']['Longitude'])

        distance_from_initial_point = distanceFromTo(Lat1, staLat, Lon1,
                                                     staLon)
        distance_from_final_point = distanceFromTo(Lat2, staLat, Lon2, staLon)

        sta['value']['Distance_From_Initial_Point'] = round(
            distance_from_initial_point, 5)
        sta['value']['Distance_From_Final_Point'] = round(
            distance_from_final_point, 5)

        lt.addLast(initialStationSortedByDistance, sta)
        lt.addLast(finalStationSortedByDistance, sta)

    mg.mergesort(initialStationSortedByDistance, closerInitialStation)
    mg.mergesort(finalStationSortedByDistance, closerFinalStation)

    CloserStation1 = lt.lastElement(initialStationSortedByDistance)
    CloserStation2 = lt.lastElement(finalStationSortedByDistance)

    paths = djk.Dijkstra(citibike['graph'], CloserStation1['key'])
    pathTo = djk.pathTo(paths, CloserStation2['key'])
    cost = djk.distTo(paths, CloserStation2['key'])

    return CloserStation1, CloserStation2, pathTo, cost
コード例 #18
0
def puntosPorRangoFecha(analyzer, fecha1, fecha2, numero):
    fecha1 = datetime.datetime.strptime(fecha1, '%Y-%m-%d').date()
    fecha2 = datetime.datetime.strptime(fecha2, '%Y-%m-%d').date()

    lstValores = om.values(analyzer['mapaTaxi'], fecha1, fecha2)

    nueva_lista = lt.newList('SINGLE_LINKED', compararTaxi)

    itera = it.newIterator(lstValores)
    while (it.hasNext(itera)):
        elemto = it.next(itera)
        lista = elemto['lstidtaxi']

        itera2 = it.newIterator(lista)
        while (it.hasNext(itera2)):
            valor = it.next(itera2)

            id_taxi = valor['idtaxi']
            puntos = valor["puntos"]

            pos = lt.isPresent(nueva_lista, id_taxi)
            if pos == 0:
                salida = {"idtaxi": None, "puntos": None}
                salida["idtaxi"] = id_taxi
                salida["puntos"] = puntos
                lt.addLast(nueva_lista, salida)
            else:
                salida = lt.getElement(nueva_lista, pos)
                salida["puntos"] = salida["puntos"] + puntos

    #ordenar lista de salida
    merSort.mergesort(nueva_lista, compararvalores)

    itera = it.newIterator(nueva_lista)
    i = 1
    resultado = []

    while (it.hasNext(itera)):
        valor = it.next(itera)
        salida = {}
        salida['Taxi'] = valor['idtaxi']
        salida['puntos'] = valor['puntos']
        resultado.append(salida)
        if i >= numero:
            break
        i = i + 1

    return resultado
コード例 #19
0
def para_mantenimiento(citibike, fecha, ide):
    fecha = str_to_python_time(fecha)
    arbol = om.get(citibike["mapa_fecha"], fecha)
    arbol = me.getValue(arbol)
    mapa = m.get(arbol, ide)
    grafo = me.getValue(mapa)
    arcos = gr.edges(grafo)

    horas_organizadas = lt.newList("ARRAY_LIST")
    camino_organizado = lt.newList("ARRAY_LIST")
    for i in range(1, lt.size(arcos) + 1):
        elemento = lt.getElement(arcos, i)
        corre_hora = str(elemento["inicio"])
        corre_hora = datetime.datetime.strptime(corre_hora, "%H:%M:%S.%f")
        corre_hora = datetime.datetime.time(corre_hora)
        lt.addLast(horas_organizadas, corre_hora)
    mge.mergesort(horas_organizadas, comparador_horas)

    for i in range(1, lt.size(horas_organizadas) + 1):
        hora = lt.getElement(horas_organizadas, i)
        for e in range(1, lt.size(arcos) + 1):
            arco = lt.getElement(arcos, e)
            corre_hora = str(arco["inicio"])
            corre_hora = datetime.datetime.strptime(corre_hora, "%H:%M:%S.%f")
            corre_hora = datetime.datetime.time(corre_hora)
            arco["inicio"] = corre_hora
            if corre_hora == hora:
                lt.addLast(camino_organizado, arco)

    for i in range(1, lt.size(camino_organizado) + 1):
        elemento = lt.getElement(camino_organizado, i)
        if i == 1:
            parqueada = conver_to_seconds(elemento["inicio"])
            usada = conver_to_seconds(elemento["final"]) - conver_to_seconds(
                elemento["inicio"])
        else:

            usada += conver_to_seconds(elemento["final"]) - conver_to_seconds(
                elemento["inicio"])

            parqueada += conver_to_seconds(
                elemento["inicio"]) - conver_to_seconds(
                    (lt.getElement(camino_organizado, i - 1))["final"])
        if i == lt.size(camino_organizado):
            resta = conver_to_seconds("23:59:59")
            parqueada += resta - conver_to_seconds(elemento["final"])

    return (usada, parqueada, camino_organizado)
コード例 #20
0
def buscar_estaciones_top_ingreso(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)
        nombre = conversor_id_nombre(vert, reference_table)
        lt.addLast(estaciones, (estacion, nombre))
    merge.mergesort(estaciones, lessFunction)
    final_top = []
    for i in range(3):
        top = lt.lastElement(estaciones)
        final_top.append(top)
        lt.removeLast(estaciones)
    return final_top
コード例 #21
0
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
コード例 #22
0
def EstaciónMasProxima(latO, lonO, analyzer):
    idynombre = []
    prox = lt.newList(datastructure="ARRAY_LIST", cmpfunction=comparador)
    Index = analyzer["index"]
    A = m.keySet(Index)
    a = it.newIterator(A)
    while it.hasNext(a):
        B = it.next(a)
        C = m.get(Index, B)
        B = me.getValue(C)
        latitud = B["start station latitude"]
        longitud = B["start station longitude"]
        distancia = ha.haversine(float(lonO), float(latO), float(longitud), float(latitud))
        B["Distancia al punto"] = distancia
        lt.addLast(prox, B)
    merge.mergesort(prox, MasProximo)
    resultado = lt.firstElement(prox)
    idynombre.append(resultado["start station name"])
    idynombre.append(resultado["start station id"])
    return idynombre
コード例 #23
0
def topViajes(dataBase) -> tuple:
    stations = dataBase['station']
    topIn = list.newList()
    topOut = list.newList()
    topTrips = list.newList()
    keys = map.keySet(stations)
    keys = listiterator.newIterator(keys)
    while listiterator.hasNext(keys):
        key = listiterator.next(keys)
        station = map.get(stations, key)
        station = mapentry.getValue(station)
        list.addFirst(topIn, {
            'station': station['name'],
            'value': station['tripsIn']
        })
        list.addFirst(topOut, {
            'station': station['name'],
            'value': station['tripsOut']
        })
        list.addFirst(topTrips, {
            'station': station['name'],
            'value': station['trips']
        })
    mergesort.mergesort(topIn, Comparation.tripsVal)
    mergesort.mergesort(topOut, Comparation.tripsVal)
    mergesort.mergesort(topTrips, Comparation.tripsVal)

    return (topIn, topOut, topTrips)
コード例 #24
0
def parteB_consultaB(inicial, fecha_ini, fecha_fin, topN):
    fecha_fin = datetime.datetime.strptime(fecha_fin, "%Y-%m-%d")
    fecha_fin = fecha_fin.date()

    fecha_ini = datetime.datetime.strptime(fecha_ini, "%Y-%m-%d")
    fecha_ini = fecha_ini.date()

    datos_mitad = om.values(inicial["fechas"], fecha_ini, fecha_fin)
    datos = m.newMap(maptype="PROBING", comparefunction=compararEstacions2)
    for dic in range(1, lt.size(datos_mitad) + 1):
        lista = lt.getElement(datos_mitad, dic)
        lista = m.valueSet(lista)

        for ele in range(1, lt.size(lista) + 1):
            dato = lt.getElement(lista, ele)
            obtenido = m.get(datos, dato["taxi"])
            if obtenido == None:
                m.put(datos, dato["taxi"], dato)
            else:
                obtenido = me.getValue(obtenido)
                nodo_antes_servicio = obtenido["puntos"] / obtenido["servicios"]
                nodo_ahora_servicio = dato["puntos"] / dato["servicios"]
                nuevo = nodo_ahora_servicio + nodo_antes_servicio
                nuevo *= (obtenido["servicios"] + dato["servicios"])
                nuevo_nodo = {
                    "taxi": obtenido["taxi"],
                    "puntos": nuevo,
                    "servicios": obtenido["servicios"] + dato["servicios"]
                }
                m.put(datos, nuevo_nodo["taxi"], nuevo_nodo)
    list_final = lt.newList("ARRAY_LIST")
    ordenado = m.valueSet(datos)
    mergesort.mergesort(ordenado, comparador_puntos)
    for dato_ in range(1, lt.size(ordenado) + 1):
        candidato = lt.getElement(ordenado, dato_)
        lt.addLast(list_final, candidato)
        if dato_ == topN:
            break
    return list_final
コード例 #25
0
def hallarTop(tabla, numero):
    taxis = m.keySet(tabla)
    puntos = m.valueSet(tabla)
    mrg.mergesort(puntos, lessfunction)
    listaOrd = lt.newList(datastructure="ARRAY_LIST")
    i = 0
    while i < numero:
        F = lt.lastElement(puntos)
        lt.addLast(listaOrd, F)
        lt.removeLast(puntos)
        i += 1
    listaTaxis = lt.newList(datastructure="ARRAY_LIST")
    itelistapuntos = it.newIterator(listaOrd)
    while it.hasNext(itelistapuntos):
        G = it.next(itelistapuntos)
        itetop = it.newIterator(taxis)
        while it.hasNext(itetop):
            H = it.next(itetop)
            I = m.get(tabla, H)
            J = me.getValue(I)
            if J == G:
                lt.addLast(listaTaxis, H)
    return listaTaxis
def getPointsV2(database: DataBase, date1, date2) -> dict:
    days = database.getDays()
    days = orderedmap.values(days, date1, date2)
    days = lti.newIterator(days)
    top = map.newMap(comparefunction=cmp.compareId)
    while lti.hasNext(days):
        day = lti.next(days).points
        day = map.valueSet(day)
        day = lti.newIterator(day)
        while lti.hasNext(day):
            wallet = lti.next(day)
            if map.contains(top, wallet.id):
                node = map.get(top, wallet.id)
                value = mapentry.getValue(node)
                value['points'] += wallet.points
            else:
                value = {'id': wallet.id, 'points': wallet.points}

                map.put(top, wallet.id, value)

    top = map.valueSet(top)
    sort.mergesort(top, cmp.points)
    return top
コード例 #27
0
def puntosPorFecha(analyzer, fecha, numero):
    fecha = datetime.datetime.strptime(fecha, '%Y-%m-%d').date()
    entry = om.get(analyzer['mapaTaxi'], fecha)
    valor = me.getValue(entry)
    lsttaxis = valor['lstidtaxi']

    merSort.mergesort(lsttaxis, compararvalores)

    itera = it.newIterator(lsttaxis)
    i = 1
    resultado = []

    while (it.hasNext(itera)):
        valor = it.next(itera)
        salida = {}
        salida['Taxi'] = valor['idtaxi']
        salida['puntos'] = valor['puntos']
        resultado.append(salida)
        if i >= numero:
            break
        i = i + 1

    return resultado
コード例 #28
0
def sortVideos(catalog, size, tipo, cmpfunction):
    if size != "None":
        sub_list = lt.subList(catalog['videos'], 0, size)
    else:
        sub_list = catalog
    sub_list = sub_list.copy()
    if tipo == 1:
        sorted_list = se.selection_sort(sub_list, cmpfunction)
    elif tipo == 2:
        sorted_list = it.insertion_sort(sub_list, cmpfunction)
    elif tipo == 3:
        sorted_list = sa.shell_sort(sub_list, cmpfunction)
    elif tipo == 4:
        sorted_list = qu.sort(sub_list, cmpfunction)
    elif tipo == 5:
        sorted_list = me.mergesort(sub_list, cmpfunction)
    return sorted_list
コード例 #29
0
def getBestVideos(catalog, num, opcionsort):
    """
    Retorna los mejores videos
    """
    sub_list = lt.subList(catalog['videos'], 1, num)
    sub_list = sub_list.copy()
    start_time = time.process_time()
    if opcionsort == 4:
        nsblista = ms.mergesort(sub_list, cmpVideosByViews)
    elif opcionsort == 5:
        nsblista = qs.quicksortf(sub_list, cmpVideosByViews)
    elif opcionsort == 1:
        nsblista = sortselect(sub_list, cmpVideosByViews)
    elif opcionsort == 2:
        nsblista = sortinsert(sub_list, cmpVideosByViews)
    elif opcionsort == 3:
        nsblista = sortshell(sub_list, cmpVideosByViews)
    stop_time = time.process_time()
    elapsed_time_mseg = (stop_time - start_time) * 1000
    return elapsed_time_mseg, nsblista
コード例 #30
0
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