def conocer_a_director(lista, lista2, nombre_director):
    if lista['size'] == 0:
        print("La lista esta vacía")
        return 0
    else:
        counter = 0
        votos_p = 0
        lista_final = lt.newList("ARRAY-LIST")
        iterador = it.newIterator(lista)
        while it.hasNext(iterador):
            element = it.next(iterador)

            if element["director_name"].lower() == nombre_director.lower():
                id1 = element["id"]
                iterador2 = it.newIterator(lista2)
                while it.hasNext(iterador2):
                    element2 = it.next(iterador2)
                    id2 = element2["id"]
                    if id1 == id2:
                        lt.addLast(lista_final, element2)
                        counter += 1
                        voto = float(element2["vote_average"])
                        votos_p += voto
    promedio = votos_p / counter

    return lista_final, counter, promedio
Esempio n. 2
0
def getMoviesByActor(catalog,actor_name):
    actorMoviesID=[]
    totalRating=0
    actorDirectors={}
    iterator = it.newIterator(catalog["actors"])
    while it.hasNext(iterator):
        element = it.next(iterator)
        if actor_name.lower() in element["actor_name"].lower(): #filtrar por palabra clave 
            actorMoviesID.append(element["movie_id"])
    iterator = it.newIterator(catalog["movies"])
    while it.hasNext(iterator):
        element=it.next(iterator)
        if element["id"] in actorMoviesID:
            totalRating+=float(element["vote_average"])
    iterator = it.newIterator(catalog["directors"])
    while it.hasNext(iterator):
        element = it.next(iterator)
        if element["movie_id"] in actorMoviesID and element["director_name"] not in actorDirectors:
            actorDirectors[element["director_name"]]=1
        if element["movie_id"] in actorMoviesID and element["director_name"] in actorDirectors:
            actorDirectors[element["director_name"]]+=1
        
        
    


    if len(actorMoviesID)>0:
        return print("Ha estado en",len(actorMoviesID),"películas y su promedio es de",round(totalRating/len(actorMoviesID),3), ". Ha sido dirigido más veces por: ",max(actorDirectors,key=actorDirectors.get))
    else:
        return "No tiene películas"
Esempio n. 3
0
def newDijkstra(graph, s):
    """
    Crea una busqueda Dijkstra para un digrafo y un vertice origen
    """
    prime = nextPrime (g.numVertex(graph) * 2)
    search = {'graph':graph, 's':s, 'visitedMap':None, 'minpq':None}
    search['visitedMap'] = map.newMap(numelements=prime, maptype='PROBING', comparefunction=graph['comparefunction'])
    vertices = g.vertices (graph)
    itvertices = it.newIterator (vertices)
    while (it.hasNext (itvertices)):
        vert =  it.next (itvertices)
        map.put (search['visitedMap'], vert, {'marked':False,'edgeTo':None,'distTo':math.inf})
    map.put(search['visitedMap'], s, {'marked':True,'edgeTo':None,'distTo':0})
    pq = minpq.newIndexMinPQ(g.numVertex(graph), comparenames)
    search['minpq'] = pq
    minpq.insert(search['minpq'], s, 0)
    while not minpq.isEmpty(search['minpq']):
        v = minpq.delMin(pq)
        if not g.containsVertex(graph,v):
            raise Exception("Vertex ["+v+"] is not in the graph")
        else:
            adjs = g.adjacentEdges(search['graph'],v)
            adjs_iter = it.newIterator (adjs) 
            while (it.hasNext(adjs_iter)):
                w = it.next (adjs_iter)
                relax(search, w)


        # obtener los enlaces adjacentes de v
        # Iterar sobre la lista de enlaces
        # Relajar (relax) cada enlace
    return search
    def test_invertedElements_greater(self):
        """
        Lista ordenada inversamente
        """
        self.lst = slt.newList(self.list_type)
        slt.addFirst(self.lst, self.movie1)
        slt.addFirst(self.lst, self.movie2)
        slt.addFirst(self.lst, self.movie3)
        slt.addFirst(self.lst, self.movie4)
        slt.addFirst(self.lst, self.movie5)
        slt.addFirst(self.lst, self.movie6)

        print(
            "Inverted list:----------------------------------------------------"
        )
        iterator = it.newIterator(self.lst)
        while it.hasNext(iterator):
            element = it.next(iterator)
            result = "".join(
                str(key) + ": " + str(value) + ",  "
                for key, value in element.items())
            print(result)
        print("sorting ....")
        sort.shellSort(self.lst, self.greater)
        iterator = it.newIterator(self.lst)
        while it.hasNext(iterator):
            element = it.next(iterator)
            result = "".join(
                str(key) + ": " + str(value) + ",  "
                for key, value in element.items())
            print(result)
Esempio n. 5
0
def trips_per_dates(catalog, init_date, last_date):
    '''
    Función que responde el requerimiento 2; para un rango de fechas devuelve la cantidad de viajes totales por ciudad
    '''
    # Esta es la que usamos para responder el req 2 , se devulve un dict con llaves = ciudades y value = suma de todas las cantidades

    response = {}
    date_1 = strToDate(init_date, '%m/%d/%Y')
    date_2 = strToDate(last_date, '%m/%d/%Y')
    range_list = tree.valueRange(catalog['date_city_trips'], date_1, date_2,
                                 greater)
    #print(range_list)
    #print(type(range_list))
    iterator_range = it.newIterator(range_list)
    while it.hasNext(iterator_range):
        Element = it.next(iterator_range)
        elkeys = map.keySet(Element)
        iterator_keys = it.newIterator(elkeys)
        while it.hasNext(iterator_keys):
            city = it.next(iterator_keys)
            count = map.get(Element, city)['value']
            if city in response:
                r = response[city]
                w = r + count
                response[city] = w
            else:
                response[city] = count

    return response
Esempio n. 6
0
def peliculas_por_actor(listaActores, listaPeliculas, nombreActor):

    pos_actor = lt.isPresent(listaActores, nombreActor)
    actor = lt.getElement(listaActores, pos_actor)

    itera = it.newIterator(actor["peliculas"])
    print("Contidad de peliculas actor ", nombreActor, ": ",
          actor["peliculas"]["size"], "\n")

    average = 0

    while it.hasNext(itera):
        id_pelicula = it.next(itera)
        posicion = lt.isPresent(listaPeliculas, id_pelicula)
        peliculas = lt.getElement(listaPeliculas, posicion)
        average += float(peliculas["vote_average"])
        print(peliculas["original_title"])

    promedio = average / actor["peliculas"]["size"]
    print("El promedio de todas sus peliculas es:\n", promedio)

    #con que directores ha trabajado mas
    itera = it.newIterator(actor["director"])

    while it.hasNext(itera):
        diretor = it.next(itera)
        print("director ", diretor)

    shell.shellSort1(actor["director"], greater, "count")

    print("Director con mas colaboraciones:\n")
    print(lt.getElement(actor["director"], 1))
    def test_orderedElements(self):
        """
        Lista ordenada
        """
        self.lst = slt.newList(self.list_type)
        slt.addFirst(self.lst, self.movie6)
        slt.addFirst(self.lst, self.movie5)
        slt.addFirst(self.lst, self.movie4)
        slt.addFirst(self.lst, self.movie3)
        slt.addFirst(self.lst, self.movie2)
        slt.addFirst(self.lst, self.movie1)

        print(
            "ordered list:----------------------------------------------------"
        )
        iterator = it.newIterator(self.lst)
        while it.hasNext(iterator):
            element = it.next(iterator)
            result = "".join(
                str(key) + ": " + str(value) + ",  "
                for key, value in element.items())
            print(result)
        print("sorting ....")
        sort.selectionSort(self.lst, self.less)
        iterator = it.newIterator(self.lst)
        while it.hasNext(iterator):
            element = it.next(iterator)
            result = "".join(
                str(key) + ": " + str(value) + ",  "
                for key, value in element.items())
            print(result)
def Conocer_un_director(lst, lst2, criteria):
    """
    Retorna una lista con cierta cantidad de elementos ordenados por el criterio
    """
    t1 = process_time()
    cont = 0
    valor = 0
    lista = []
    print("\n")
    ite = it.newIterator(lst2)
    while it.hasNext(ite):
        vote = it.next(ite)
        nom = vote["director_name"]
        ids = int(vote["id"])
        if criteria == vote["director_name"]:
            ite2 = it.newIterator(lst)
            while it.hasNext(ite2):
                vote2 = it.next(ite2)
                ids2 = int(vote2["id"])
                if int(ids) == int(ids2):
                    cont += 1
                    valor += float(vote2["vote_average"])
                    lista.append(vote2["original_title"])
    if cont == 0:
        promedio = valor / 1
    else:
        promedio = valor / cont
    t2 = process_time()
    print("El tiempo de procesamiento es de: ", t2 - t1)
    return str(lista) + "\nLa cantidad de películas es de: " + str(
        cont) + "\nSu promedio es de: " + str(round(promedio, 2))
Esempio n. 9
0
def know_actor(actor, lst_movies, lst_casting):
    if len(lst_movies) == 0:
        print('Las listas están vacías')
        return 0, 0
    else:
        t1_start = process_time()
        peliculas_actor = lt.newList('ARRAY_LIST')
        movies_data = lt.newList('ARRAY_LIST')
        director = lt.newList('ARRAY_LIST')
        get_actor_name_id(lst_casting, peliculas_actor, actor)
        get_actor_director(lst_casting, director, actor)
        iterator_id = it.newIterator(peliculas_actor)
        while it.hasNext(iterator_id):
            movie_id = it.next(iterator_id)
            iterator_movies = it.newIterator(lst_movies)
            while it.hasNext(iterator_movies):
                movie = it.next(iterator_movies)
                if movie_id == movie['id']:
                    lt.addLast(movies_data, movie)
        lista_directores = collections.Counter(director['elements']).most_common(1)
        director_colaboraciones = lista_directores[0][0]
        actor_movies(movies_data, actor)
        total_vote_average = movies_total_average(movies_data)
        t1_stop = process_time()
        print('Tiempo de ejecución ', t1_stop - t1_start, ' segundos')
        return movies_data['size'], total_vote_average, director_colaboraciones
Esempio n. 10
0
def find_good_movies(director, vote_average, lst_d, lst_c):
    """
    Retorna la cantidad de elementos que cumplen con un criterio para una columna dada
    """
    if len(lst_d) == 0:
        print('Las listas están vacías')
        return 0, 0
    else:
        t1_start = process_time()  # Start time.
        all_director_movies, good_movies = (lt.newList('ARRAY_LIST') for _ in range(2))
        # Search all director movie ids and add them to a list.
        get_director_movie_ids(lst_c, all_director_movies, director)
        # Search good movies and add vote points to list.
        iterator_ids = it.newIterator(all_director_movies)
        while it.hasNext(iterator_ids):
            movie_id = it.next(iterator_ids)
            iterator_movies = it.newIterator(lst_d)
            while it.hasNext(iterator_movies):
                movie = it.next(iterator_movies)
                if movie_id == movie['id']:
                    actual_vote = float(movie['vote_average'])
                    if actual_vote >= vote_average:
                        lt.addLast(good_movies, movie)
        show_movies(good_movies, director)
        # Calculate number of good movies and total vote average of director.
        total_vote_average = movies_total_average(good_movies)
        t1_stop = process_time()  # Final time.
        print('Tiempo de ejecución ', t1_stop - t1_start, ' segundos')
    return good_movies['size'], total_vote_average
    def test_oneElement_greater(self):
        """
        Un elemento
        """
        self.lst = slt.newList(self.list_type)
        slt.addFirst(self.lst, self.movie1)

        print(
            "one element:----------------------------------------------------")
        iterator = it.newIterator(self.lst)
        while it.hasNext(iterator):
            element = it.next(iterator)
            result = "".join(
                str(key) + ": " + str(value) + ",  "
                for key, value in element.items())
            print(result)
        print("sorting ....")
        sort.shellSort(self.lst, self.greater)
        iterator = it.newIterator(self.lst)
        while it.hasNext(iterator):
            element = it.next(iterator)
            result = "".join(
                str(key) + ": " + str(value) + ",  "
                for key, value in element.items())
            print(result)
Esempio n. 12
0
    def test_randomElements (self):
        """
         Lista con elementos en orden aleatorio
        """
        self.lst = slt.newList(self.list_type)
        slt.addFirst (self.lst, self.book5)
        slt.addFirst (self.lst, self.book6)
        slt.addFirst (self.lst, self.book3)
        slt.addFirst (self.lst, self.book10)
        slt.addFirst (self.lst, self.book1)
        slt.addFirst (self.lst, self.book2)
        slt.addFirst (self.lst, self.book8)
        slt.addFirst (self.lst, self.book4)
        slt.addFirst (self.lst, self.book7)
        slt.addFirst (self.lst, self.book9)

     
        print ("Random list:----------------------------------------------------")
        iterator = it.newIterator(self.lst)
        while  it.hasNext(iterator):
            element = it.next(iterator)
            result = "".join(str(key) + ": " + str(value) + ",  " for key, value in element.items())
            print (result)
        print ("sorting ....")
        sort.mergesort  (self.lst, self.less)
        iterator = it.newIterator(self.lst)
        while  it.hasNext(iterator):
            element = it.next(iterator)
            result = "".join(str(key) + ": " + str(value) + ",  " for key, value in element.items())
            print (result)
Esempio n. 13
0
def know_director(director, lst_d, lst_c):
    """
    Retorna la cantidad de elementos que cumplen con un criterio para una columna dada
    """
    if len(lst_d) == 0:
        print('Las listas están vacías')
        return 0, 0
    else:
        t1_start = process_time()  # tiempo inicial
        all_director_movies, movies_data = (lt.newList('ARRAY_LIST')
                                            for _ in range(2))
        # Search all director movie ids and add them to a list.
        get_director_movie_ids(lst_c, all_director_movies, director)
        # Search movies and add vote points to list.
        iterator_ids = it.newIterator(all_director_movies)
        while it.hasNext(iterator_ids):
            movie_id = it.next(iterator_ids)
            iterator_movies = it.newIterator(lst_d)
            while it.hasNext(iterator_movies):
                movie = it.next(iterator_movies)
                if movie_id == movie['id']:
                    lt.addLast(movies_data, movie)
        show_movies(movies_data, director)
        # Calculate number of movies and total vote average of director.
        total_vote_average = movies_total_average(movies_data)
        t1_stop = process_time()  # tiempo final
        print('Tiempo de ejecución ', t1_stop - t1_start, ' segundos')
    return movies_data['size'], total_vote_average
Esempio n. 14
0
def getAccidentsByDateRange (catalog, dates):
    
    startDate = strToDate(dates.split(" ")[0],'%Y-%m-%d')
    endDate = strToDate(dates.split(" ")[1],'%Y-%m-%d')
    dateList = tree.valueRange(catalog['dateTree'], startDate, endDate, greater)
   # print(dateList)
    #hol= lt.getElement(dateList,13)
    #print(hol)
    iteraDates = it.newIterator(dateList)
    cities = {}
    count = 0
    while it.hasNext(iteraDates):
        dateElement = it.next(iteraDates)
        if dateElement:
            citiesList = map.keySet(dateElement['cityMap'])
            iteraCities = it.newIterator(citiesList)
            while it.hasNext(iteraCities):
                cityKey = it.next(iteraCities)
                new = map.get(dateElement['cityMap'],cityKey,compareByKey)
                count += new
                if cityKey in cities.keys():
                    cities[cityKey] += new
                else:
                    cities[cityKey]=new
                #response += ''+str(cityKey) + ':' + str(map.get(dateElement['cityMap'],cityKey,compareByKey)) + '\n'
    response = 'Total de accidentes en el rango: '+str(count)+'\n'
    for i in cities:
        response += str(i)+": "+str(cities[i])+"\n"
            #print (i, cities[i])
            #response += str(i[0])+": "+str(i[1])+"\n"
        
    return response
    def test_randomElements(self):
        """
         Lista con elementos en orden aleatorio
        """
        self.lst = slt.newList(self.list_type)
        slt.addFirst(self.lst, self.movie5)
        slt.addFirst(self.lst, self.movie6)
        slt.addFirst(self.lst, self.movie3)
        slt.addFirst(self.lst, self.movie4)
        slt.addFirst(self.lst, self.movie1)
        slt.addFirst(self.lst, self.movie2)

        print(
            "Random list:----------------------------------------------------")
        iterator = it.newIterator(self.lst)
        while it.hasNext(iterator):
            element = it.next(iterator)
            result = "".join(
                str(key) + ": " + str(value) + ",  "
                for key, value in element.items())
            print(result)
        print("sorting ....")
        sort.shellSort(self.lst, self.less)
        iterator = it.newIterator(self.lst)
        while it.hasNext(iterator):
            element = it.next(iterator)
            result = "".join(
                str(key) + ": " + str(value) + ",  "
                for key, value in element.items())
            print(result)
    def test_repeatedElements_greater(self):
        """
           Con muchos elementos en la lista
        """
        self.lst = slt.newList(self.list_type)
        slt.addFirst(self.lst, self.movie5)
        slt.addFirst(self.lst, self.movie4)
        slt.addFirst(self.lst, self.movie6)
        slt.addFirst(self.lst, self.movie3)
        slt.addFirst(self.lst, self.movie1)
        slt.addFirst(self.lst, self.movie6)
        slt.addFirst(self.lst, self.movie2)
        slt.addFirst(self.lst, self.movie4)

        print(
            "Repeated elements:----------------------------------------------------"
        )
        iterator = it.newIterator(self.lst)
        while it.hasNext(iterator):
            element = it.next(iterator)
            result = "".join(
                str(key) + ": " + str(value) + ",  "
                for key, value in element.items())
            print(result)
        print("sorting ....")
        sort.shellSort(self.lst, self.greater)
        iterator = it.newIterator(self.lst)
        while it.hasNext(iterator):
            element = it.next(iterator)
            result = "".join(
                str(key) + ": " + str(value) + ",  "
                for key, value in element.items())
            print(result)
Esempio n. 17
0
    def test_invertedElements (self):
        """
        Lista ordenada inversamente
        """
        self.lst = slt.newList(self.list_type)
        slt.addFirst (self.lst, self.book1)
        slt.addFirst (self.lst, self.book2)
        slt.addFirst (self.lst, self.book3)
        slt.addFirst (self.lst, self.book4)
        slt.addFirst (self.lst, self.book5)
        slt.addFirst (self.lst, self.book6)
        slt.addFirst (self.lst, self.book7)
        slt.addFirst (self.lst, self.book8)
        slt.addFirst (self.lst, self.book9)
        slt.addFirst (self.lst, self.book10)

        print ("Inverted list:----------------------------------------------------")
        iterator = it.newIterator(self.lst)
        while  it.hasNext(iterator):
            element = it.next(iterator)
            result = "".join(str(key) + ": " + str(value) + ",  " for key, value in element.items())
            print (result)
        print ("sorting ....")
        sort.shellSort (self.lst, self.less)
        iterator = it.newIterator(self.lst)
        while  it.hasNext(iterator):
            element = it.next(iterator)
            result = "".join(str(key) + ": " + str(value) + ",  " for key, value in element.items())
            print (result)
def countElementsByCriteria(criteria, column, lst, lst2):
    """
    Retorna la cantidad de elementos que cumplen con un criterio para una columna dada
    """
    if lst['size'] == 0:
        print("La lista esta vacía")
        return 0
    else:

        t1_start = process_time()  #tiempo inicial
        counter = 0
        iterador = it.newIterator(lst)
        while it.hasNext(iterador):
            element = it.next(iterador)
            if criteria.lower() in element[column].lower(
            ):  #filtrar por palabra clave
                id1 = element["id"]
                iterator2 = it.newIterator(lst2)
                while it.hasNext(iterator2):
                    element2 = it.next(iterator2)
                    id2 = element2["id"]
                    if id1 == id2:
                        if float(element2["vote_average"]) >= 6:
                            counter += 1
        t1_stop = process_time()  #tiempo final

    return counter
Esempio n. 19
0
    def test_repeatedElements (self):
        """
           Con muchos elementos en la lista
        """
        self.lst = slt.newList(self.list_type)
        slt.addFirst (self.lst, self.book5)
        slt.addFirst (self.lst, self.book6)
        slt.addFirst (self.lst, self.book14)
        slt.addFirst (self.lst, self.book3)
        slt.addFirst (self.lst, self.book13)
        slt.addFirst (self.lst, self.book10)
        slt.addFirst (self.lst, self.book1)
        slt.addFirst (self.lst, self.book12)
        slt.addFirst (self.lst, self.book2)
        slt.addFirst (self.lst, self.book8)
        slt.addFirst (self.lst, self.book4)
        slt.addFirst (self.lst, self.book11)
        slt.addFirst (self.lst, self.book7)
        slt.addFirst (self.lst, self.book9)

        print ("Repeated elements:----------------------------------------------------")
        iterator = it.newIterator(self.lst)
        while  it.hasNext(iterator):
            element = it.next(iterator)
            result = "".join(str(key) + ": " + str(value) + ",  " for key, value in element.items())
            print (result)
        print ("sorting ....")
        sort.shellSort (self.lst, self.less)
        iterator = it.newIterator(self.lst)
        while  it.hasNext(iterator):
            element = it.next(iterator)
            result = "".join(str(key) + ": " + str(value) + ",  " for key, value in element.items())
            print (result)
Esempio n. 20
0
def getMoviesByDirector (catalog, dir_name):
    """
    Retorna las peliculas a partir del nombre del director
    """
    directorMoviesID=[]
    totalRating=0
    iterator = it.newIterator(catalog["directors"])
    while it.hasNext(iterator):
        element = it.next(iterator)
        if dir_name.lower() in element["director_name"].lower(): #filtrar por palabra clave 
             directorMoviesID.append(element["movie_id"])
    iterator = it.newIterator(catalog["movies"])
    while it.hasNext(iterator):
        element=it.next(iterator)
        if element["id"] in directorMoviesID:
            totalRating+=float(element["vote_average"])

    if len(directorMoviesID)>0:
        return print("Ha dirigido",len(directorMoviesID),"películas y su promedio es de",round(totalRating/len(directorMoviesID),3))
    else:
        return "No tiene películas"

    if len(directorMoviesID)>0:
        return print("Ha dirigido",len(directorMoviesID),"películas y su promedio es de",round(totalRating/len(directorMoviesID),3))
    else:
        return "No tiene películas"
def ConocerAUnDirector(nombredirector, lstmoviescasting, lstmoviesdetails):
    IteradorCasting = it.newIterator(lstmoviescasting)
    IDsDirector = lt.newList()
    while it.hasNext(IteradorCasting) == True:
        elemento = it.next(IteradorCasting)
        if elemento['director_name'].upper() == nombredirector.upper():
            lt.addLast(IDsDirector, elemento["id"])
    lt.addLast(IDsDirector, -1)
    IteradorDetalles = it.newIterator(lstmoviesdetails)
    IteradorID = it.newIterator(IDsDirector)
    nombresanospuntajes = lt.newList()
    numero = it.next(IteradorID)
    while it.hasNext(IteradorID):
        pelicula = it.next(IteradorDetalles)
        if pelicula["id"] == numero:
            tripla = (pelicula["title"], pelicula["release_date"][-4:],
                      pelicula["vote_average"])
            lt.addLast(nombresanospuntajes, tripla)
            numero = it.next(IteradorID)
    lt.addLast(nombresanospuntajes, -1)
    IteradorNAP = it.newIterator(nombresanospuntajes)
    nombresanos = lt.newList()
    numeropeliculas = lt.size(nombresanospuntajes) - 1
    ADividir = 0
    while it.hasNext(IteradorNAP):
        tripla = it.next(IteradorNAP)
        if type(tripla) == tuple:
            lt.addLast(nombresanos, (tripla[0] + " (" + tripla[1] + ")"))
            ADividir += float(tripla[2])
    lt.addLast(nombresanos, -1)
    return ((nombresanos, numeropeliculas, ADividir / numeropeliculas))
Esempio n. 22
0
def ConocerDirector(criteria, column, lst, lst2):  #Conocer un director

    lista_id = []
    if lst['size'] == 0:
        print("La lista esta vacía")
        return 0
    else:
        t1_start = process_time()  #tiempo inicial
        counter = 0
        iterator = it.newIterator(lst)
        while it.hasNext(iterator):
            element = it.next(iterator)
            if criteria.lower() in element["director_name"].lower():
                counter += 1
                lista_id.append((element["id"]))
        lista_peliculas = []
        lista_promedio = []
        iterator = it.newIterator(lst2)
        while it.hasNext(iterator):
            element = it.next(iterator)
            if element["id"] in lista_id:
                lista_peliculas.append(element["original_title"])
                lista_promedio.append(element["vote_average"])
        lista_promedio1 = map(float, lista_promedio)
        promedio_final = sum(lista_promedio1) / len(lista_promedio)
        t1_stop = process_time()  #tiempo final
    print("Tiempo de ejecución ", t1_stop - t1_start, " segundos")
    return lista_peliculas, counter, promedio_final
def conocer_un_actor(lista, lista2, nombre_actor):
    if lista['size'] == 0:
        print("La lista esta vacía")
        return 0
    else:
        autor = {'Nombre': nombre_actor, "Peliculas": None, "Directores": None}
        peliculas = lt.newList("ARRAY_LIST")
        Directores = lt.newList("ARRAY_LIST", cmpfunction=cmp1)
        conteo = 0
        sumatoria = 0
        iterador = it.newIterator(lista)
        while it.hasNext(iterador):
            elemento = it.next(iterador)
            encontre = False
            i = 1
            while i <= 5 and not encontre:
                actor = elemento["actor" + str(i) + "_name"]
                if actor.lower() == nombre_actor.lower():
                    encontre = True
                i += 1
            if encontre == True:
                id1 = elemento["id"]
                director = elemento["director_name"]
                iterador2 = it.newIterator(lista2)
                encontro2 = False
                while it.hasNext(iterador2) and not encontro2:
                    elemento2 = it.next(iterador2)
                    id2 = elemento2["id"]
                    if id1 == id2:
                        encontro2 = True
                        lt.addLast(peliculas, elemento2)
                        conteo += 1
                        sumatoria += float(elemento2["vote_average"])
                        iterador4 = it.newIterator(Directores)
                        encontro3 = False
                        while it.hasNext(iterador4) and not encontro3:
                            elemento4 = it.next(iterador4)
                            if director == elemento4["nombre"]:
                                encontro3 = True
                        if encontro3 == False:
                            lt.addLast(Directores, {
                                "nombre": director,
                                "conteo": 0
                            })
                        iterador3 = it.newIterator(Directores)
                        while it.hasNext(iterador3):
                            elemento3 = it.next(iterador3)
                            if director == elemento3["nombre"]:
                                elemento3["conteo"] += 1

        sort.insertionSort(Directores, greater_director)
        mas = lt.getElement(Directores, 1)
        autor["Peliculas"] = peliculas
        autor["Directores"] = Directores
        promedio = sumatoria / conteo

    return autor, mas, conteo, promedio
Esempio n. 24
0
def moviesByActor(casting, details):
    peliculas_dirigidas_por_x_director = lt.newList('SINGLE_LINKED', None)
    actor = input("Ingrese el actor:\n")

    t1_start = process_time()

    iter = listiterator.newIterator(casting)
    while listiterator.hasNext(iter):
        d = listiterator.next(iter)
        if d["actor1_name"] == actor or d["actor2_name"] == actor or d[
                "actor3_name"] == actor or d["actor4_name"] == actor or d[
                    "actor5_name"] == actor:
            lt.addFirst(peliculas_dirigidas_por_x_director, d)

    peliculas = lt.newList('SINGLE_LINKED', None)

    directores = {}

    iter1 = listiterator.newIterator(peliculas_dirigidas_por_x_director)
    while listiterator.hasNext(iter1):
        ide = listiterator.next(iter1)

        iter2 = listiterator.newIterator(details)
        while listiterator.hasNext(iter2):
            p = listiterator.next(iter2)

            if ide["id"] == p["id"]:
                lt.addFirst(peliculas, p)
                print(p["original_title"])
                if ide["director_name"] in directores:
                    directores[ide["director_name"]] += 1
                else:
                    directores[ide["director_name"]] = 1

    #encontrar directores pelis
    maximo_colab = max(directores, key=directores.get)

    #encontrar los datos

    numero_peliculas_director = lt.size(peliculas)
    suma_promedio_voto = 0

    iter = listiterator.newIterator(peliculas)
    while listiterator.hasNext(iter):
        s = listiterator.next(iter)
        suma_promedio_voto += float(s["vote_average"])

    promedio_pelis = 0
    if (numero_peliculas_director > 0):
        promedio_pelis = suma_promedio_voto / numero_peliculas_director

    #print("Peliculas dirigidas por "+ director +": " + str(peliculas['title'])) Encontrar los nombres de las peliculas
    print("Numero de películas de " + actor + ": " +
          str(numero_peliculas_director))
    print("Promedio de calificación de las peliculas del actor: " +
          str(promedio_pelis))
    print("el director con mayor número de colaboraciones es: " + maximo_colab)
Esempio n. 25
0
def moviesByDirector(director,casting,details):
    """
    Función 3
    Conocer a un director
    director: nombre del director

    Como aficionado del cine Quiero
    conocer el trabajo de un director.
    """

    peliculas_dirigidas_por_x_director = lt.newList('SINGLE_LINKED', None)
    
    iter = listiterator.newIterator(casting)
    while listiterator.hasNext(iter):
        d = listiterator.next(iter)
        if d["director_name"] == director:
            lt.addFirst(peliculas_dirigidas_por_x_director, d)
        

    peliculas = lt.newList('SINGLE_LINKED', None)



    iter1 = listiterator.newIterator(peliculas_dirigidas_por_x_director)
    while listiterator.hasNext(iter1):
        ide = listiterator.next(iter1)

    iter2 = listiterator.newIterator(details)
    while listiterator.hasNext(iter2):
        p = listiterator.next(iter2)

        if ide["id"] == p["id"]:
            lt.addFirst(peliculas, p)
            print (p["original_title"])
            


    #encontrar los datos

    numero_peliculas_director = lt.size(peliculas)
    suma_promedio_voto = 0
 

    iter = listiterator.newIterator(peliculas)
    while listiterator.hasNext(iter):
        s = listiterator.next(iter)
        suma_promedio_voto += float(s["vote_average"])


    promedio_pelis = 0
    if(numero_peliculas_director > 0):
        promedio_pelis = suma_promedio_voto/numero_peliculas_director
    resultado = {}
    resultado["Numero de películas de "+ director] = numero_peliculas_director
    resultado["Promedio de calificación de las peliculas del director "] = promedio_pelis
    return resultado
def orderElementsByCriteria(function, column, lst, elements):
    """
    Retorna una lista con cierta cantidad de elementos ordenados por el criterio
    """
    if lst['size'] == 0:
        print("La lista esta vacía")
        return 0
    else:

        t1_start = process_time()  #tiempo inicial
        lista = lt.newList()
        if column == "vote_count" and function.lower() == "acendente":
            sort.insertionSort(lst, less)
            iterador = it.newIterator(lst)
            counter = 1
            while it.hasNext(iterador) and counter <= int(elements):
                element = it.next(iterador)
                lt.addLast(lista, element)

                counter += 1
            hola = lt.subList(lst, 1, int(elements))
        elif column == "vote_count" and function.lower() == "decendente":
            sort.insertionSort(lst, greater1)
            iterador = it.newIterator(lst)
            counter = 1
            while it.hasNext(iterador) and counter <= int(elements):
                element = it.next(iterador)
                lt.addLast(lista, element)
                counter += 1

        elif column == "vote_average" and function.lower() == "acendente":
            sort.insertionSort(lst, less2)
            iterador = it.newIterator(lst)
            counter = 1
            while it.hasNext(iterador) and counter <= int(elements):
                element = it.next(iterador)
                lt.addLast(lista, element)
                counter += 1

        elif column == "vote_average" and function.lower() == "decendente":
            sort.insertionSort(lst, greater2)
            iterador = it.newIterator(lst)
            counter = 1
            while it.hasNext(iterador) and counter <= int(elements):
                element = it.next(iterador)
                lt.addLast(lista, element["vote_average"])
                counter += 1

        t1_stop = process_time()  #tiempo final
        print("Tiempo de ejecución ", t1_stop - t1_start, " segundos")
    print(lt.size(hola))
    return hola
def loadCSVFile(file, file2, sep=";"):
    """
    Carga un archivo csv a una lista
    Args:
        file
            Archivo csv del cual se importaran los datos
        sep = ";"
            Separador utilizado para determinar cada objeto dentro del archivo
        Try:
        Intenta cargar el archivo CSV a la lista que se le pasa por parametro, si encuentra algun error
        Borra la lista e informa al usuario
    Returns: None  
    """
    #lst = lt.newList("ARRAY_LIST") #Usando implementacion arraylist
    catalog = mg.newCatalog()  #Usando implementacion linkedlist
    print("Cargando archivo ....")
    t1_start = process_time()  #tiempo inicial
    dialect = csv.excel()
    dialect.delimiter = sep
    if 1:
        with open(file, encoding="utf-8") as csvfile:
            spamreader = csv.DictReader(csvfile, dialect=dialect)
            for row in spamreader:
                lt.addLast(catalog["Peliculas"], row)
        lista = []
        with open(file2, encoding="utf-8") as csvfile:
            spamreader = csv.DictReader(csvfile, dialect=dialect)
            for row2 in spamreader:
                nombre = row2["director_name"]
                id1 = row2["id"]
                iterador = it.newIterator(catalog["Peliculas"])
                while it.hasNext(iterador):
                    pelicula = it.next(iterador)
                    id2 = pelicula["id"]
                    if id1 == id2:
                        mg.add_Movie_director(catalog, nombre, pelicula,
                                              mg.compareauthors)

        print("Hubo un error con la carga del archivo")
    t1_stop = process_time()  #tiempo final
    print("Tiempo de ejecución ", t1_stop - t1_start, " segundos")
    count = 1
    print(lt.size(catalog["Directores"]))

    iterador3 = it.newIterator(catalog["Directores"])
    while it.hasNext(iterador3) and count == 1:
        director = it.next(iterador3)
        print(director["name"]["Peliculas"])
        count += 1

    catalog["Directores"]
    return catalog
Esempio n. 28
0
def show_movies(movies, director):
    if director is not None:
        print('Las películas dirigidas por', director, 'son:')
        iterator = it.newIterator(movies)
        while it.hasNext(iterator):
            element = it.next(iterator)
            print('-', element['title'])
    else:
        iterator = it.newIterator(movies)
        while it.hasNext(iterator):
            element = it.next(iterator)
            print('-', element['title'] + ':',
                  '\n   con un puntaje promedio de', element['vote_average'],
                  'y un total de', element['vote_count'], 'votaciones')
Esempio n. 29
0
def edges(graph):
    """
    Retorna una lista con todos los arcos del grafo graph
    """
    lstmap = map.valueSet(graph['vertices'])
    lstresp = lt.newList()
    itervertex = it.newIterator(lstmap)
    while it.hasNext(itervertex):
        lstedge = it.next(itervertex)
        iteredge = it.newIterator(lstedge)
        while (it.hasNext(iteredge)):
            edge = it.next(iteredge)
            if not (lt.isPresent(lstresp, edge, e.compareedges)):
                lt.addLast(lstresp, edge)
    return lstresp
Esempio n. 30
0
def countElementsFilteredByColumn(criteria, column, lst):
    """
    Retorna cuantos elementos coinciden con un criterio para una columna dada  
    Args:
        criteria:: str
            Critero sobre el cual se va a contar la cantidad de apariciones
        column
            Columna del arreglo sobre la cual se debe realizar el conteo
        list
            Lista en la cual se realizará el conteo, debe estar inicializada
    Return:
        counter :: int
            la cantidad de veces ue aparece un elemento con el criterio definido
    """
    if lst['size']==0:
        print("La lista esta vacía")  
        return 0
    else:
        t1_start = process_time() #tiempo inicial
        counter=0
        iterator = it.newIterator(lst)
        while  it.hasNext(iterator):
            element = it.next(iterator)
            if criteria.lower() in element[column].lower(): #filtrar por palabra clave 
                counter+=1           
        t1_stop = process_time() #tiempo final
        print("Tiempo de ejecución ",t1_stop-t1_start," segundos")
    return counter