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)
예제 #2
0
def path(mapa,lista, source, dst):
    if source == dst:
        return lista
    vertice= map.get(mapa, source)
    anterior= vertice['edgeTo']
    lt.addFirst(lista, anterior)
    path(mapa,lista,anterior,dst)
예제 #3
0
def crear_lista(camino):
    
    lista = lt.newList('SINGLE_LINKED', None)
    with open(camino, encoding="utf-8-sig") as csvfile:
        reader = csv.DictReader(csvfile, delimiter=';')
        for row in reader:
            lt.addFirst(lista, row)
    return lista
def test_addFirst(lst, books):
    assert lt.isEmpty(lst) == True
    assert lt.size(lst) == 0
    lt.addFirst(lst, books[1])
    assert lt.size(lst) == 1
    lt.addFirst(lst, books[2])
    assert lt.size(lst) == 2
    book = lt.firstElement(lst)
    assert book == books[2]
예제 #5
0
def obtener_peliculas_mejor_votadas (list, number):
    movies = lista_ordenada_vote_average(list)
    peliculas_mejores_calificaciones_ascendente= lt.newList("ARRAY_LIST")
    peliculas_mejores_calificaciones_descendente= lt.newList("ARRAY_LIST")
    for cont in range (1, number+1):
        tuple1=("Id: ",lt.getElement (movies, cont)[0]["id"],"Title: ",lt.getElement (movies, cont)[1]["original_title"],"Vote_Average: ",lt.getElement (movies, cont)[1]["vote_average"]  )
        lt.addFirst (peliculas_mejores_calificaciones_ascendente, tuple1)
        lt.addLast (peliculas_mejores_calificaciones_descendente, tuple1)
    return (peliculas_mejores_calificaciones_descendente["elements"],peliculas_mejores_calificaciones_ascendente["elements"])
예제 #6
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(data, less):
    t1_start = process_time()
    sort(data, less)
    ranking = lt.newList("SINGLE_LINKED")
    for i in range(1, 11):
        lt.addFirst(ranking, lt.getElement(data, i))

    t1_stop = process_time()  #tiempo final
    print("Tiempo de ejecución ", t1_stop - t1_start, " segundos")
    return ranking
예제 #8
0
def ranking_las_mas_votadas_del_genero(lista,genero_buscado,number):
    lista_ordenada_vote_count_genero= ordenar_peliculas_genero_vote_count(lista,genero_buscado)
    mas_votadas_del_genero_ascendente=lt.newList("ARRAY_LIST")
    mas_votadas_del_genero_descendente=lt.newList("ARRAY_LIST")
    for k in range(1, number+1):
        element=lt.getElement(lista_ordenada_vote_count_genero,k)
        tuple1=("Titulo:",element[1]["original_title"], "Vote Count: ",element[1]["vote_count"], "Genero: ",element[1]["genres"])
        lt.addFirst(mas_votadas_del_genero_ascendente,tuple1)
        lt.addLast(mas_votadas_del_genero_descendente,tuple1)
    return (mas_votadas_del_genero_ascendente["elements"],mas_votadas_del_genero_descendente["elements"])
예제 #9
0
def conocerAUnActor(lst, lst1, criteria):
    "requerimiento 4"
    if lst['size'] == 0 or lst1['size'] == 0:
        print("lista vacia")
    else:
        director = lt.newList()
        t1_start = process_time()
        cont = 0
        suma = 0.0
        prom = 0.0
        directorname = ""
        for i in range(lst1['size']):
            elemento = lt.getElement(lst1, i)
            if elemento['actor1_name'] == criteria or elemento[
                    'actor2_name'] == criteria or elemento[
                        'actor3_name'] == criteria or elemento[
                            'actor4_name'] == criteria or elemento[
                                'actor5_name'] == criteria:
                namedic = elemento['director_name']
                if director['size'] == 0 or director == None:
                    lt.addFirst(director, {'name': namedic, 'veces': 1})
                else:
                    if existe(director, 'name', namedic):
                        for dir in director:
                            if dir['name'] == namedic:
                                dir['veces'] += 1
                                break
                    else:
                        lt.addLast(director, {'name': namedic, 'veces': 1})

                id = int(elemento['id'])
                for j in range(lst['size']):
                    elemento1 = lt.getElement(lst, j)
                    if int(elemento1['id']) == id:
                        cont += 1
                        suma += float(elemento1['vote_average'])
                        print(str(cont) + ": " + elemento1['original_title'])
                        break

        mas = 0
        for i in range(director['size']):
            element = lt.getElement(director, i)
            if int(element['veces']) > mas:
                directorname = element['name']

        t1_stop = process_time()  #tiempo final
        print("\nTiempo de ejecución ", t1_stop - t1_start, " segundos")
        if (cont == 0):
            prom = 0
        else:
            prom = (suma / cont)
    print("\nEl actor tiene " + str(cont) +
          " peliculas y su calificación media es " + str(prom) +
          "\n el director con quien mas ha grabado es: " + directorname)
예제 #10
0
def req6(lst1, criteria1, column1, function, criteriaf, n):
    porgenero = lt.newList("ARRAY_LIST")
    iterator = it.newIterator(lst1)
    lt.addFirst(porgenero, '')
    while it.hasNext(iterator):
        element = it.next(iterator)
        if criteria1.lower() in element[column1].lower():
            lt.addLast(porgenero, element)
    lt.removeFirst(porgenero)
    listado = req2(porgenero, function, criteriaf, n)
    return listado
예제 #11
0
def obtener_peliculas_peor_votadas (list, number):
    movies = lista_ordenada_vote_average(list)
    peliculas_peor_calificadas_ascendente= lt.newList("ARRAY_LIST")
    peliculas_peor_calificadas_descendente= lt.newList("ARRAY_LIST")
    si= int(lt.size(movies))
    inf= si - number
    for k in range (inf+1, si+1):
        tuple1=("Id: ",lt.getElement (movies, k)[0]["id"],"Title: ",lt.getElement (movies, k)[1]["original_title"],"Vote_Average: ",lt.getElement (movies, k)[1]["vote_average"]  )
        lt.addLast (peliculas_peor_calificadas_descendente, tuple1)
        lt.addFirst (peliculas_peor_calificadas_ascendente, tuple1)
    return (peliculas_peor_calificadas_descendente["elements"],peliculas_peor_calificadas_ascendente["elements"])
예제 #12
0
def ranking_las_peor_votadas_del_genero(lista,genero_buscado,number):
    lista_ordenada_vote_average_genero= ordenar_peliculas_genero_vote_average(lista,genero_buscado)
    peor_votadas_del_genero_ascendente=lt.newList("ARRAY_LIST")
    peor_votadas_del_genero_descendente=lt.newList("ARRAY_LIST")
    si= int(lt.size(lista_ordenada_vote_average_genero))
    inf= si-number
    for k in range(inf+1, si+1):
        element=lt.getElement(lista_ordenada_vote_average_genero,k)
        tuple1=("Titulo:",element[1]["original_title"], "Vote Average: ",element[1]["vote_average"], "Genero: ",element[1]["genres"])
        lt.addFirst(peor_votadas_del_genero_descendente,tuple1)
        lt.addLast(peor_votadas_del_genero_ascendente,tuple1)
    return (peor_votadas_del_genero_ascendente["elements"],peor_votadas_del_genero_descendente["elements"])
예제 #13
0
def mejoresgenero(lista, parametro, genero):

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

    iter = listiterator.newIterator(lista)
    while listiterator.hasNext(iter):
        d = listiterator.next(iter)
        if genero in d["genres"]:
            lt.addFirst(peliculas_del_genero, d)
    
    r = crear_ranking2(peliculas_del_genero, parametro)
    return r
        
def Ranking_del_genero(lst, criteria, orden):
    lista = lt.newList('ARRAY_LIST')
    i = 0
    while i < lt.size(lst):
        valor = lt.getElement(lst, i)
        if criteria in valor["genres"]:
            lt.addFirst(lista, valor)
        i += 1
    a = 0
    b = 0
    c = 0
    d = 0
    lista2 = []
    lista3 = []
    if orden == "mayor":
        ls.shellSort(lista, topMovies)
        for i in range(1, 11):
            dato = lt.getElement(lista, i)
            a += int(dato["vote_count"])
            lista2.append(dato['original_title'] + ": " + dato['vote_count'])
            #print (dato['original_title'] + ": " + dato['vote_count'])
        promedio = a / 10
        count = "\nEl promedio del count es: " + str(promedio)
        ls.shellSort(lista, topMoviesAve)
        for i in range(1, 6):
            dato = lt.getElement(lista, i)
            b += float(dato["vote_average"])
            lista3.append(dato['original_title'] + ": " + dato['vote_average'])
            #print (dato['original_title'] + ": " + dato['vote_average'])
        promedio2 = b / 5
        average = "\nEl promedio del average es: " + str(promedio2)
    elif orden == "menor":
        ls.shellSort(lista, lowMovies)
        for i in range(1, 11):
            dato = lt.getElement(lista, i)
            c += int(dato["vote_count"])
            lista2.append(dato['original_title'] + ": " + dato['vote_count'])
            #print (dato['original_title'] + ": " + dato['vote_count'])
        promedio3 = c / 10
        count = "\nEl promedio del count es: " + str(promedio3)
        ls.shellSort(lista, lowMoviesAve)
        for i in range(1, 6):
            dato = lt.getElement(lista, i)
            d += float(dato["vote_average"])
            lista3.append(dato['original_title'] + ": " + dato['vote_average'])
            #print (dato['original_title'] + ": " + dato['vote_average'])
        promedio4 = d / 5
        average = "\nEl promedio del average es: " + str(promedio4)
    return "\nSus películas por count: \n" + str(
        lista2) + count + "\nSus películas por average: \n" + str(
            lista3) + average
예제 #15
0
def el_camino(mapa, origen, final):
    """ Retorna el camino entre dos nodos"""
    r = hasPathTo_2(mapa, origen, final)
    if r == False:
        return None
    elif r == True:
        escalas = lt.newList('ARRAYLIST')
        v = final
        while v != origen:
            lt.addFirst(escalas, v)
            w = map.get(mapa, v)
            v = w['edgeTo']
        lt.addFirst(escalas, origen)
    return escalas
예제 #16
0
def path_small(catalog, source, dst):

    mapa = catalog['marcas_bfs']
    path = catalog['path_bfs']
    if dst == source:
        return path
    if mapa == None:
        carga_bfs(catalog, source)
    nod_bus = map.get(mapa, dst)
    if nod_bus != None:
        new_node = nod_bus['predecesor']
        lt.addFirst(path, new_node)
        getPath(catalog, source, new_node)
    else:
        return None
예제 #17
0
def consulta_temperature(catalog, n):
    '''
    Función que devuelve los N días con la mayor y menor temperatura
    '''
    N = int(n)
    list_temperatures = catalog['list_temperature']
    response_max = lt.newList('ARRAY_LIST')
    response_min = lt.newList('ARRAY_LIST')
    for i in range(1, N + 1):
        g = lt.getElement(list_temperatures, i)
        lt.addLast(response_max, g)
    s = int(lt.size(list_temperatures))
    for i in range(s - N, s):
        f = lt.getElement(list_temperatures, i)
        lt.addFirst(response_min, f)
    return (response_max, response_min)
예제 #18
0
    def test_oneElement (self):
        """
        Un elemento
        """
        self.lst = slt.newList(self.list_type)
        slt.addFirst (self.lst, self.book1)

        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.insertionSort (self.lst, self.less)
        iterator = it.newIterator(self.lst)
        self.assertTrue(self.verifySorting(self.lst, self.less))
예제 #19
0
def moviesByGenre(genero,casting,details):
    """
    
    Funcion 5:
    genero: género de intéres
    casting: info del archivo csv casting
    details: info del archivo csv details cleaned

    Como aficionado del cine Quiero
    entender las características de un
    genero de películas.

    Las condicionesson:
    −El nombre del genero
    cinematográfico (genres).

    """

    peliculas_del_genero = lt.newList('SINGLE_LINKED', None)
    iter = listiterator.newIterator(details)
    while listiterator.hasNext(iter):
        d = listiterator.next(iter)
        if genero in d["genres"]:
            lt.addFirst(peliculas_del_genero, d)
            print(d["original_title"])


    numero_peliculas_genero = lt.size(peliculas_del_genero)
    suma_promedio_voto = 0
    nombres_peliculas = []

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

    promedio_vote_count = 0
    if(numero_peliculas_genero > 0):
        promedio_vote_count = suma_promedio_voto/numero_peliculas_genero

    #mostrar la lista
    respuesta = {}
    respuesta['Numero de películas asociadas al género '+ genero] = numero_peliculas_genero
    respuesta["Promedio de votos de las peliculas del género "+ genero] = promedio_vote_count
    return respuesta
예제 #20
0
def Add_station_list(catalog, row):
    if map.contains(catalog['map_station'], row['city']) == None:
        value = lt.newList()
        map.put(catalog['map_station'], row['city'], value)
        dic = {
            'city_id': row['id'],
            'dock_count': row['dock_count'],
            'city': row['city']
        }
        lista = map.get(catalog['map_station'], row['city'])
        lt.addFirst(lista, dic)
    else:
        lista = map.get(catalog['map_station'], row['city'])
        dic = {
            'city_id': row['id'],
            'dock_count': row['dock_count'],
            'city': row['city']
        }
        lt.addFirst(lista, dic)
예제 #21
0
def getPath(catalog, source, dst):
    """
    Retorna el camino, si existe, entre vertice origen y destino
    """
    mapa = catalog['marcas_dfs']
    grafo = catalog['reviewGraph']
    path = catalog['path_dfs']
    if dst == source:
        return path
    if map.size(mapa) == 0:
        dbs.depth_first_search(grafo, mapa, source)

    nod_bus = map.get(mapa, dst)
    if nod_bus != None:
        new_node = nod_bus['predecesor']
        lt.addFirst(path, new_node)
        getPath(catalog, source, new_node)

    else:
        return None
예제 #22
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.insertionSort(lst, less)
    iterator = it.newIterator(lst)
    while it.hasNext(iterator):
        element = it.next(iterator)
        assert element == book1
예제 #23
0
def req_3(catalog, dias):
    lista = catalog['list_temepratura']
    respuesta = lt.newList()

    for i in range(1, dias):
        dic = lt.getElement(lista, i)
        fecha = dic['dia']
        pos = i
        temperatura = dic['temperature']
        res = {'posicion': pos, 'fecha': fecha, 'temperatura': temperatura}
        lt.addFirst(respuesta, res)

    tamaño = lt.size(lista)
    for i in range(tamaño, tamaño - int(dias)):
        dic = lt.getElement(lista, i)
        fecha = dic['dia']
        pos = -i
        temperatura = dic['temperature']
        res = {'posicion': pos, 'fecha': fecha, 'temperatura': temperatura}
        lt.addFirst(respuesta, res)
    return respuesta
예제 #24
0
def getPath (catalog, source, dst):
    """
    Retorna el camino, si existe, entre vertice origen y destino
    """
    mapa= catalog['marcas_dfs']
    grafo= catalog['reviewGraph']
    path= catalog['path_dfs']
    if dst==source:
        return path
    if map.size(mapa)==0:
        dbs.depth_first_search(grafo,mapa,source)

    nod_bus =map.get(mapa, dst)
    if nod_bus != None:
        new_node= nod_bus['predecesor']
        lt.addFirst(path,new_node)
        getPath(catalog,source,new_node)

    def carga_bfs(catalog, source):
    search= dbs.newBFS(catalog['reviewGraph'], source)
    catalog['marcas_bfs']= search['visitedMap']

def path_small(catalog, source, dst):

    mapa= catalog['marcas_bfs']
    path= catalog['path_bfs']
    if dst==source:
        return path
    if mapa == None:
        carga_bfs(catalog, source)
    nod_bus=map.get(mapa, dst) 
    if nod_bus != None:
        new_node= nod_bus['predecesor']
        lt.addFirst(path,new_node)
        path_small(catalog,source,new_node)
    else:
        return None
예제 #25
0
def cargar_listaDirectores(file, sep=";"):
    lst = lt.newList('SINGLE_LINKED', comparar_director)

    dialect = csv.excel()
    dialect.delimiter = sep

    try:
        with open(file, encoding="utf-8") as csvfile:
            spamreader = csv.DictReader(csvfile, dialect=dialect)
            for row in spamreader:
                director = {}
                director["nombre"] = row["director_name"]
                posicion1 = lt.isPresent(lst, director["nombre"])

                if posicion1 == 0:
                    director["ids_peliculas"] = lt.newList()
                    lt.addLast(director["ids_peliculas"], row['id'])
                    lt.addFirst(lst, director)
                else:
                    director = lt.getElement(lst, posicion1)
                    lt.addLast(director["ids_peliculas"], row['id'])
    except:
        print("Hubo un error con la carga del archivo")
    return lst
예제 #26
0
def add_day_temperature(catalog, row):
    elemento = {'dia': row['date'], 'temperature': row['mean_temperature_f']}
    lt.addFirst(catalog['list_temepratura'], elemento)
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.shellSort(lst, less)
    probarOrden(lst)
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.shellSort(lst, less)
    probarOrden(lst)
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.shellSort(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) == book13
    assert slt.removeFirst(lst) == book9
    assert slt.removeFirst(lst) == book10
    assert slt.removeFirst(lst) != book14
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.shellSort(lst, less)
    probarOrden(lst)