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)
 def test_sort_menor_a_mayor(self):
     """
      Lista con elementos en orden aleatorio
     """
     print("sorting ....")
     sort.mergesort(self.lst_movies, self.greater)
     self.printList(self.lst_movies)
def ranking_genero(genero: str, num_peliculas: int, lst1: list, lst2: list,
                   criterio: int):

    t1_start = process_time()  #tiempo inicial
    movies_lt = lt.newList(datastructure='ARRAY_LIST', cmpfunction=None)
    j = 1
    filas = len(lst1)
    while j < filas:
        elemento = lst1[j]["genres"]
        if genero in elemento:
            movie_name = lst1[j]["original_title"]
            movie_vote_average = float(lst1[j]["vote_average"])
            movie_vote_count = float(lst1[j]["vote_count"])

            movie = {
                'movie_name': movie_name,
                'vote_average': movie_vote_average,
                'vote_count': movie_vote_count
            }
            lt.addLast(movies_lt, movie)
        j = j + 1

    if criterio == 1:
        mg.mergesort(movies_lt, greater_num)
    if criterio == 2:
        mg.mergesort(movies_lt, greater_rating)

    pedazo_mejores = lt.subList(movies_lt, 1, num_peliculas)
    pos_inicial_peores = lt.size(movies_lt) - num_peliculas
    pedazo_peores = lt.subList(movies_lt, pos_inicial_peores, num_peliculas)

    t1_stop = process_time()  #tiempo final
    print("Tiempo de ejecución ", t1_stop - t1_start, " segundos")
    return pedazo_mejores["elements"], pedazo_peores["elements"]
def ranking_peliculas2(num_peliculas: int, lst1: list, lst2: list,
                       criterio2: int):
    t1_start = process_time()  #tiempo inicial
    movies_lt = lt.newList(datastructure='ARRAY_LIST', cmpfunction=None)
    i = 1
    filas = len(lst1)
    while i < filas:
        movie_name = lst1[i]["original_title"]
        movie_vote_average = float(lst1[i]["vote_average"])
        movie_vote_count = float(lst1[i]["vote_count"])
        movie = {
            'movie_name': movie_name,
            'vote_average': movie_vote_average,
            'vote_count': movie_vote_count
        }
        lt.addLast(movies_lt, movie)
    i = i + 1
    if criterio2 == 1:
        mg.mergesort(movies_lt, mejor_calificada)
    if criterio2 == 2:
        mg.mergesort(movies_lt, peor_calificada)
    conjunto_mejores_calificadas = lt.subList(movies_lt, 1, num_peliculas)
    pos_inicial_peores_calificadas = lt.size(movies_lt) - num_peliculas
    conjunto_peores_calificadas = lt.subList(movies_lt,
                                             pos_inicial_peores_calificadas,
                                             num_peliculas)
    t1_stop = process_time()  #tiempo final
    print("Tiempo de ejecución ", t1_stop - t1_start, " segundos")
    return conjunto_mejores_calificadas[
        "elements"], conjunto_peores_calificadas["elements"]
Esempio n. 5
0
def test_randomElements():
    """
    Lista con elementos en orden aleatorio, prueba que se ordene correctamente cuando no hay orden alguno
    """
    lst = slt.newList(list_type)
    slt.addFirst(lst, book5)
    slt.addFirst(lst, book6)
    slt.addFirst(lst, book3)
    slt.addFirst(lst, book10)
    slt.addFirst(lst, book1)
    slt.addFirst(lst, book2)
    slt.addFirst(lst, book8)
    slt.addFirst(lst, book4)
    slt.addFirst(lst, book7)
    slt.addFirst(lst, book9)

    print("Random list:----------------------------------------------------")
    iterator = it.newIterator(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(lst, less)
    probarOrden(lst)
Esempio n. 6
0
def test_invertedElements():
    """
    Lista ordenada inversamente, sale correcta si el orden final es el inverso a la forma en la cual se
    agregan
    """
    lst = slt.newList(list_type)
    slt.addFirst(lst, book1)
    slt.addFirst(lst, book2)
    slt.addFirst(lst, book3)
    slt.addFirst(lst, book4)
    slt.addFirst(lst, book5)
    slt.addFirst(lst, book6)
    slt.addFirst(lst, book7)
    slt.addFirst(lst, book8)
    slt.addFirst(lst, book9)
    slt.addFirst(lst, book10)

    print("Inverted list:----------------------------------------------------")
    iterator = it.newIterator(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(lst, less)
    iterator = it.newIterator(lst)
    probarOrden(lst)
Esempio n. 7
0
    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.mergesort(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. 8
0
    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.mergesort(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. 9
0
    def test_randomElements_greater(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.mergesort(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. 10
0
    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.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. 11
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.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. 12
0
 def test_sort(self):
     """
      Lista con elementos en orden aleatorio
     """
     print("sorting ....")
     sort.mergesort(self.lst_books, self.less)
     self.printList(self.lst_books)
Esempio n. 13
0
def test_orderedElementss():
    """
    Lista ordenada normalmente, deberia ser igual a como se ingresan los libros
    """
    lst = slt.newList(list_type)
    slt.addFirst(lst, book10)
    slt.addFirst(lst, book9)
    slt.addFirst(lst, book8)
    slt.addFirst(lst, book7)
    slt.addFirst(lst, book6)
    slt.addFirst(lst, book5)
    slt.addFirst(lst, book4)
    slt.addFirst(lst, book3)
    slt.addFirst(lst, book2)
    slt.addFirst(lst, book1)

    print("Inverted list:----------------------------------------------------")
    iterator = it.newIterator(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(lst, less)
    probarOrden(lst)
Esempio n. 14
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.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. 15
0
def sortHash (catalog):
    #Iterar tabla de hash, extraer lista de llaves, ordenar cada lista de tuplas con mergeSort
    citiesList = map.keySet(catalog['capacityMap'])
    citiesIter = it.newIterator(citiesList)
    while it.hasNext(citiesIter):
        i_city = it.next(citiesIter)
        stationCapacityList = map.get(catalog['capacityMap'], i_city)['value']
        mergesort.mergesort(stationCapacityList, compareByTuple)
Esempio n. 16
0
def loadData (catalog):
    """
    Carga los datos de los archivos en la estructura de datos
    """
    #loadLibraries(catalog)
    loadCities(catalog)
    loadArbol(catalog)
    loadTrips(catalog)
    loadWeather(catalog)
    sort.mergesort(catalog["List"], comparemayor)
Esempio n. 17
0
def crear_ranking(lst, function):
    iterador = it.newIterator(lst)
    lista = lt.newList()
    while it.hasNext(iterador) == True:
        dato = it.next(iterador)
        lt.addLast(lista, dato)
    if lt.size(lista) > 0:
        ms.mergesort(lista, function)
        return lista
    else:
        return -1
Esempio n. 18
0
def sortCityStations(catalog):
    '''
    Función que ordena la lista de estaciones para cada ciudad por dock cont de mayor a menor
    '''
    #Iteramos sobre toda las ciudades para ir ordenando las listas de estaciones por dock_count
    cityStationsMap = catalog['cities']
    citiesList = map.keySet(cityStationsMap)
    citiesIterator = it.newIterator(citiesList)
    while it.hasNext(citiesIterator):
        city = it.next(citiesIterator)
        stationsList = map.get(cityStationsMap, city)['value']
        mergesort.mergesort(stationsList, compareDockCountGreater)
Esempio n. 19
0
def test_loading_CSV_y_ordenamiento():
    """
    Prueba que se pueda leer el archivo y que despues de relizar el sort, el orden este correcto
    """
    setUp()
    sort.mergesort(lst_books, less)
    while not (lt.isEmpty(lst_books)):
        x = int(lt.removeLast(lst_books)['goodreads_book_id'])
        if not (lt.isEmpty(lst_books)):
            y = int(lt.lastElement(lst_books)['goodreads_book_id'])
        else:
            break
        assert x > y
def CrearRankingPeliculas(NPeliculasRanking, Criterio, TipoDeOrdenamiento,
                          lstmoviesdetails):
    if Criterio == "COUNT" and TipoDeOrdenamiento == "ASCENDENTE":
        MeSo.mergesort(lstmoviesdetails, CountFunctionMenMay)
    elif Criterio == "COUNT" and TipoDeOrdenamiento == "DESCENDENTE":
        MeSo.mergesort(lstmoviesdetails, CountFunctionMayMen)
    elif Criterio == "AVERAGE" and TipoDeOrdenamiento == "ASCENDENTE":
        MeSo.mergesort(lstmoviesdetails, AverageFunctionMenMay)
    elif Criterio == "AVERAGE" and TipoDeOrdenamiento == "DESCENDENTE":
        MeSo.mergesort(lstmoviesdetails, AverageFunctionMayMen)
    if Criterio == "COUNT": SopaDeMacacoUmaDeliciaKKKK = "vote_count"
    elif Criterio == "AVERAGE": SopaDeMacacoUmaDeliciaKKKK = "vote_average"
    iterable = it.newIterator(lstmoviesdetails)
    ListaAImprimir = lt.newList()
    while int(iterable["current_node"]) < (NPeliculasRanking - 1):
        pelicula = it.next(iterable)
        tripla = (pelicula["title"], pelicula["release_date"][-4:],
                  pelicula[SopaDeMacacoUmaDeliciaKKKK])
        lt.addLast(ListaAImprimir, tripla)
    lt.addLast(ListaAImprimir, -1)
    IteradorNAP = it.newIterator(ListaAImprimir)
    nombresanos = lt.newList()
    while it.hasNext(IteradorNAP):
        tripla = it.next(IteradorNAP)
        if type(tripla) == tuple:
            lt.addLast(nombresanos,
                       ((tripla[0] + " (" + tripla[1] + ")"), tripla[2]))
    lt.addLast(nombresanos, -1)
    return (nombresanos)
Esempio n. 21
0
def orderGender(list, maome, criteria, column):
    "requerimiento 6"
    if (maome == 0):
        ms.mergesort(list, mayor, column)
        rep = 0
        promedio = 0
        calificacion = 0.0
        for i in range(list['size']):
            pelicula = lt.getElement(list, i)
            if rep >= 10:
                break
            generos = pelicula['genres'].split("|")
            for genero in generos:
                if genero.strip() == criteria:
                    rep += 1
                    promedio = int(pelicula['vote_count'])
                    calificacion += float(pelicula['vote_average'])
                    print(
                        str(rep) + ". " + pelicula['title'] + ", tiene : " +
                        pelicula['vote_count'] +
                        " votos y su calificacion es: " +
                        pelicula['vote_average'])
                    break
        print("el promedio de votos es : " + str((promedio / 10)) +
              " y su calificacion promedio es: " + str((calificacion / 10.0)))

    else:
        ms.mergesort(list, menor, column)
        rep = 0
        promedio = 0
        calificacion = 0.0
        for i in range(list['size']):
            pelicula = lt.getElement(list, i)
            if rep >= 10:
                break
            generos = pelicula['genres'].split("|")
            for genero in generos:
                if genero.strip() == criteria:
                    rep += 1
                    promedio = int(pelicula['vote_count'])
                    calificacion += float(pelicula['vote_average'])
                    print(
                        str(rep) + ". " + pelicula['title'] + ", tiene : " +
                        pelicula['vote_count'] +
                        " votos y su calificacion es: " +
                        pelicula['vote_average'])
                    break
        print("el promedio de votos es : " + str((promedio / 10)) +
              " y su calificacion promedio es: " + str((calificacion / 10.0)))
Esempio n. 22
0
def order(list, maome, column):
    "requerimiento 2"
    if (maome == 0):
        ms.mergesort(list, mayor, column)
        for i in range(10):
            pelicula = lt.getElement(list, i)
            print(
                str(i + 1) + ". " + pelicula['title'] + ": " +
                pelicula[column])
    else:
        ms.mergesort(list, menor, column)
        for i in range(10):
            pelicula = lt.getElement(list, i)
            print(
                str(i + 1) + ". " + pelicula['title'] + ": " +
                pelicula[column])
Esempio n. 23
0
def test_ManyElements():
    """
    Con muchos elementos en la lista, en donde identificadores se repiten
    Deben aparecer consecutivos aquellos con id igual
    """
    lst = slt.newList(list_type)
    slt.addFirst(lst, book5)
    slt.addFirst(lst, book6)
    slt.addFirst(lst, book14)
    slt.addFirst(lst, book3)
    slt.addFirst(lst, book13)
    slt.addFirst(lst, book10)
    slt.addFirst(lst, book1)
    slt.addFirst(lst, book12)
    slt.addFirst(lst, book2)
    slt.addFirst(lst, book8)
    slt.addFirst(lst, book4)
    slt.addFirst(lst, book11)
    slt.addFirst(lst, book7)
    slt.addFirst(lst, book9)

    print(
        "Repeated elements:----------------------------------------------------"
    )
    iterator = it.newIterator(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(lst, less)
    assert slt.removeFirst(lst) == book1
    assert slt.removeFirst(lst) == book2
    assert slt.removeFirst(lst) == book3
    assert slt.removeFirst(lst) == book4
    assert slt.removeFirst(lst) == book5
    assert slt.removeFirst(lst) == book6
    assert slt.removeFirst(lst) == book7
    assert slt.removeFirst(lst) == book11
    assert slt.removeFirst(lst) == book8
    assert slt.removeFirst(lst) == book12
    assert slt.removeFirst(lst) == book9
    assert slt.removeFirst(lst) == book13
    assert slt.removeFirst(lst) == book10
    assert slt.removeFirst(lst) == book14
Esempio n. 24
0
def loadBooks(catalog):
    """
    Carga los libros del archivo.  Por cada libro se toman sus autores y por 
    cada uno de ellos, se crea en la lista de autores, a dicho autor y una
    referencia al libro que se esta procesando.
    """
    booksfile = cf.data_dir + 'GoodReads/books.csv'
    input_file = csv.DictReader(open(booksfile))
    for book in input_file:
        # Se adiciona el libro a la lista de libros
        lt.addLast(catalog['books'], book)
        # Se obtienen los autores del libro
        authors = book['authors'].split(",")
        # Cada autor, se crea en la lista de libros del catalogo, y se
        # crea un libro en la lista de dicho autor (apuntador al libro)
        for author in authors:
            model.addBookAuthor(catalog, author.strip(), book, compareauthors)
    sort.mergesort(catalog['books'], compareratings)
def test_loading_CSV_y_ordenamiento():
    """
    Prueba que se pueda leer el archivo y que despues de relizar el sort, el orden este correcto
    """
    setUp()
    sort.mergesort(lst_books,less)
    while not (lt.isEmpty(lst_books)):
        x = int(lt.removeLast(lst_books)['goodreads_book_id'])
        if not (lt.isEmpty(lst_books)):
            y = int(lt.lastElement(lst_books)['goodreads_book_id'])
        else:
            break
        assert x > y
    counter=1
    iterador=it.newIterator(lst_books)
    while it.hasNext(iterador) and counter<=10:
        elemento=it.next(iterador)
        print(elemento)
        counter+=1
Esempio n. 26
0
def test_oneElement():
    """
    Se prueba el ordenamiento de un elemento, solo deberia haber un elemento en la lista
    """
    lst = slt.newList(list_type)
    slt.addFirst(lst, book1)

    print("one element:----------------------------------------------------")
    iterator = it.newIterator(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(lst, less)
    iterator = it.newIterator(lst)
    while it.hasNext(iterator):
        element = it.next(iterator)
        assert element == book1
Esempio n. 27
0
def rankingPeliculas(function, lst, criteria, elements):
    """
    Retorna el ranking de películas con base en los parámetros
     Args:
        function
            Función de ordenamiento que se va a usar
        column:: str
            Columna que se usa para realiza el ordenamiento (vote_average o vote_count)   
        lst
            Lista encadenada o arreglo     
        criteria:: str
            Critero para ordenar (less o greater)
        elements:: int
            Cantidad de elementos para el ranking
    Return:
        counter :: int
            la cantidad de veces ue aparece un elemento con el criterio definido
    """
    t1_start = process_time()  #tiempo inicial
    if function == "selectionsort":
        selectionsort.selectionSort(lst, criteria)
    if function == "insertionsort":
        insertionsort.insertionSort(lst, criteria)
    if function == "mergesort":
        mergesort.mergesort(lst, criteria)
    if function == "quicksort":
        quicksort.quickSort(lst, criteria)
    if function == "shellsort":
        shellsort.shellSort(lst, criteria)
    i = 0
    ordenado = []
    while i < elements:
        i += 1
        pelicula = lt.getElement(lst, i)
        ordenado.append(pelicula)
    t1_stop = process_time()  #tiempo final
    print("Tiempo de ejecución ", t1_stop - t1_start, " segundos")
    return ordenado
Esempio n. 28
0
def test_agregarYquitar():
    """
    Prueba que al hacer varios ordnamientos el orden debe mantenerse asi se cambien los elementos
    Se requiere tener la lista ordenada, luego desordenada y probar que genera excepcion
    """
    lst = slt.newList(list_type)
    slt.addFirst(lst, book10)
    slt.addFirst(lst, book9)
    slt.addFirst(lst, book8)
    slt.addFirst(lst, book7)
    slt.addFirst(lst, book6)
    slt.addFirst(lst, book5)
    slt.addFirst(lst, book4)
    slt.addFirst(lst, book3)
    slt.addFirst(lst, book2)
    slt.addFirst(lst, book1)
    probarOrden(lst)  #Prueba que al inicio la lista esté en orden
    slt.addFirst(lst, slt.removeLast(lst))
    slt.addLast(lst, slt.removeFirst(lst))
    slt.addFirst(lst, slt.removeLast(lst))
    with pytest.raises(Exception):
        probarOrden(lst)
    sort.mergesort(lst, less)
    probarOrden(lst)
Esempio n. 29
0
def CrearRankingPelicula(calificacion, lst, orden, rango=10, seguro=False):
    """
    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
        counter = {}
        almacen = {}
        if calificacion.lower() == "peor":
            if orden == 0:
                mr.mergesort(lst, less_count)
                for i in range(1, rango + 1):
                    counter = lt.getElement(lst, i)
                    if not seguro:
                        print(f"{counter['title']}:{counter['vote_count']}")
                    almacen[counter['title']] = counter['vote_count']
            else:
                mr.mergesort(lst, less)
                for f in range(1, rango + 1):
                    counter = lt.getElement(lst, f)
                    if not seguro:
                        print(f"{counter['title']}:{counter['vote_average']}")
                    almacen[counter['title']] = counter['vote_count']
        elif calificacion.lower() == "mejor":
            if orden == 0:
                mr.mergesort(lst, greater_count)
                for i in range(1, rango + 1):
                    counter = lt.getElement(lst, i)
                    if not seguro:
                        print(f"{counter['title']}:{counter['vote_count']}")
                    almacen[counter['title']] = counter['vote_count']
            else:
                mr.mergesort(lst, greater)
                for i in range(1, rango + 1):
                    counter = lt.getElement(lst, i)
                    if not seguro:
                        print(f"{counter['title']}:{counter['vote_average']}")
                    almacen[counter['title']] = counter['vote_count']
        t1_stop = process_time()

        print(f"tiempo de ejecucion: {t1_stop-t1_start} segundos")
        return almacen
def req2(x, criteria, sentido, lst):
    """
    Retorna una lista con cierta cantidad de elementos ordenados por el criterio
    """
    res = "THE " + str(x) + " "
    if criteria == 0 and sentido == 0:
        sort.mergesort(lst, lessV)
        res = res + "WORST VOTE"
    elif criteria == 0 and sentido == 1:
        sort.mergesort(lst, greaterV)
        res = res + "BEST VOTE"
    elif criteria == 1 and sentido == 0:
        sort.mergesort(lst, lessA)
        res = res + "WORST AVERAGE"
    else:
        sort.mergesort(lst, greaterA)
        res = res + "BEST AVERAGE"

    return lt.subList(lst, 1, x), res + " Movies \n"