Exemplo n.º 1
0
class PriorityQueueShort:
    """
    Clase que implementa el funcionamiento del ADT Priority
    Queue, utilizando varias Queues, según el número de
    prioridades existentes. Serán atendidos, o tienen MAYOR
    prioridad, los Nodos que se encuentren en las Queues que
    manejen un valor de prioridad menor.
    """
    def __init__(self) -> None:
        self.priorities = SinglyLinkedList()
        self.queues = SinglyLinkedList()

    def is_empty(self) -> bool:
        return len(self) == 0

    def enqueue(self, data: object, priority: int) -> bool:
        """
        Método que adiciona un nuevo Nodo con su dato a la Queue
        correspondiente, según la prioridad que éste tendrá.
        priority → [1 > 2 > 3 > ... > n]
        """
        if type(priority) == int and priority >= 1:
            if self.is_empty() or type(data) == type(self.front()):
                maximum = 0
                for i in self.priorities:
                    maximum = i
                if priority <= maximum:
                    return self.queues.locate(priority - 1).enqueue(data)
                else:
                    self.priorities.append(maximum + 1)
                    self.queues.append(Queue())
                    return self.enqueue(data, priority)
        return False

    def dequeue(self) -> object:
        for i in self.queues:
            if not i.is_empty():
                return i.dequeue()

    def front(self) -> object:
        for i in self.queues:
            if not i.is_empty():
                return i.front()

    def __len__(self) -> int:
        cnt = 0
        for i in self.queues:
            cnt += len(i)
        return cnt

    def __str__(self) -> str:
        acm = ""
        for i in self.queues:
            acm += str(i)
        return acm
Exemplo n.º 2
0
    def postfix(self) -> str:
        """
        Método que convierte una expresión Infix a una expresión Postfix,
        haciendo uso de una Stack. Separar operandos y operadores por un
        espacio en blanco.
        """
        priorities = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3, "(": 0}
        operators_stack = Stack()

        expression_infix = self.infix()
        if not expression_infix:
            return

        infix_list = self.__split(expression_infix, " ")
        postfix_list = SinglyLinkedList()

        for i in infix_list:
            if self.__isdigit(i):
                postfix_list.append(i)
            elif i == ")":
                top = operators_stack.pop()
                while top != "(" and not operators_stack.is_empty():
                    postfix_list.append(top)
                    top = operators_stack.pop()
            elif i == "(":
                operators_stack.push(i)
            elif i in priorities:
                if operators_stack.is_empty():
                    operators_stack.push(i)
                else:
                    top = operators_stack.peek()
                    if priorities[i] > priorities[top] or i == top == "^":
                        operators_stack.push(i)
                    else:
                        while not operators_stack.is_empty():
                            top = operators_stack.peek()
                            if priorities[top] >= priorities[i]:
                                postfix_list.append(operators_stack.pop())
                            else:
                                break
                        operators_stack.push(i)

        while not operators_stack.is_empty():
            postfix_list.append(operators_stack.pop())

        expression_postfix = ""
        for i in postfix_list:
            expression_postfix += str(i) + " "

        return expression_postfix[:len(expression_postfix) - 1]
Exemplo n.º 3
0
 def mayorNota_Materia(self, lista):
     if lista.is_empty():
         print("No hay estudiantes MATRICULADOS para obtener la mayor nota")
         input()
     else:
         mayor_actual = lista.locate(0).nota
         for i in range(len(lista)):
             if mayor_actual < lista.locate(i).nota:
                 mayor_actual = lista.locate(i).nota
         mayores_notas = SinglyLinkedList()
         for i in range(len(lista)):
             if mayor_actual == lista.locate(i).nota:
                 mayores_notas.append(lista.locate(i))
         return "Reporte de estudiantes con mayor nota: \n" + str(
             mayores_notas)
Exemplo n.º 4
0
    def __init__(self):
        super().__init__(title="Tres en Raya")
        self.connect("destroy", Gtk.main_quit)

        self.alternar = 0
        self.casillas = SinglyLinkedList()
        malla = Gtk.Grid(row_homogeneous=True, column_homogeneous=True)

        for i in range(3):
            for j in range(3):
                casilla = Gtk.Button(label="")
                casilla.connect("clicked", self.on_casilla_clicked)
                malla.attach(casilla, top=i * 2, left=j * 2, height=2, width=2)
                self.casillas.append(casilla)

        self.add(malla)
Exemplo n.º 5
0
 def __init__(self, *args, **kwargs):  # (**diccionario, *Tupla)
     super().__init__(*args, **kwargs)
     # crea lo basico de una ventana a travez de super
     box_main = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
     self.add(box_main)  # self -> ventana
     # Frame para insertar estudiantes
     frm_ing = Gtk.Frame(label="Ingreso de Estudiantes",
                         margin_left=5,
                         margin_right=5)
     box_main.add(frm_ing)
     grid_ing = Gtk.Grid(column_homogeneous=True, column_spacing=10)
     lbl_cod = Gtk.Label(label="Còdigo:")
     lbl_nom = Gtk.Label(label="Nombre:")
     lbl_nota = Gtk.Label(label="Nota:")
     grid_ing.attach(child=lbl_cod, left=0, top=0, width=1, height=1)
     grid_ing.attach(child=lbl_nom, left=1, top=0, width=1, height=1)
     grid_ing.attach(child=lbl_nota, left=2, top=0, width=1, height=1)
     self.ent_cod = Gtk.Entry()
     self.ent_nom = Gtk.Entry()
     self.ent_nota = Gtk.Entry()
     grid_ing.attach(child=self.ent_cod, left=0, top=1, width=1, height=1)
     grid_ing.attach(child=self.ent_nom, left=1, top=1, width=1, height=1)
     grid_ing.attach(child=self.ent_nota, left=2, top=1, width=1, height=1)
     btn_ing = Gtk.Button(label="Ingresar")
     btn_ing.connect("clicked", self.on_btn_ing_clicked)
     grid_ing.attach(child=btn_ing, left=0, top=2, width=1, height=1)
     frm_ing.add(grid_ing)
     # creacion de la lista de estudiantes del __Colegio__
     self.estudiantes = SinglyLinkedList()
Exemplo n.º 6
0
    def __init__(self, nombre, nom_materia1, nom_materia2, nom_materia3,
                 nom_materia4):
        # CONTRUCTOR INICIALIZA LOS ELEMENTOS BASICOS
        self.nombre = nombre
        self.lista = SinglyLinkedList()

        self.nom_materia1 = nom_materia1
        self.lista_materia1 = SinglyLinkedList()

        self.nom_materia2 = nom_materia2
        self.lista_materia2 = SinglyLinkedList()

        self.nom_materia3 = nom_materia3
        self.lista_materia3 = SinglyLinkedList()

        self.nom_materia4 = nom_materia4
        self.lista_materia4 = SinglyLinkedList()
Exemplo n.º 7
0
 def __split(self, expression: str, sep: str = "") -> SinglyLinkedList:
     splited_list = SinglyLinkedList()
     if sep:
         while sep in expression:
             index = expression.find(sep)
             splited_list.append(expression[:index])
             expression = expression[index + 1:]
         splited_list.append(expression)
     else:
         for i in expression:
             splited_list.append(i)
     return splited_list
Exemplo n.º 8
0
 def __split(self, string: str, sep: str = "") -> SinglyLinkedList:
     splited_list = SinglyLinkedList()
     if sep:
         while sep in string:
             index = string.find(sep)
             splited_list.append(string[:index])
             string = string[index + 1:]
         splited_list.append(string)
     else:
         for i in string:
             splited_list.append(i)
     return splited_list
Exemplo n.º 9
0
class Colegio:
    def __init__(self, nombre, nom_materia1, nom_materia2, nom_materia3,
                 nom_materia4):
        # CONTRUCTOR INICIALIZA LOS ELEMENTOS BASICOS
        self.nombre = nombre
        self.lista = SinglyLinkedList()

        self.nom_materia1 = nom_materia1
        self.lista_materia1 = SinglyLinkedList()

        self.nom_materia2 = nom_materia2
        self.lista_materia2 = SinglyLinkedList()

        self.nom_materia3 = nom_materia3
        self.lista_materia3 = SinglyLinkedList()

        self.nom_materia4 = nom_materia4
        self.lista_materia4 = SinglyLinkedList()
        # guardar varios estudiantes

    def matricular(self, un_estudiante, indice_materia):
        if indice_materia == 1:
            if self.lista_materia1.append(un_estudiante):
                print("EL ESTUDIANTE " + un_estudiante.nombre +
                      " FUE MATRICULADO EN LA MATERIA  " + self.nom_materia1)
            else:
                print("EL ESTUDIANTE " + un_estudiante.nombre +
                      " NO FUE MATRICULADO EN LA MATERIA " + self.nom_materia1)
        if indice_materia == 2:
            if self.lista_materia2.append(un_estudiante):
                print("EL ESTUDIANTE " + un_estudiante.nombre +
                      " FUE MATRICULADO EN LA MATERIA " + self.nom_materia2)
            else:
                print("EL ESTUDIANTE " + un_estudiante.nombre +
                      " NO FUE MATRICULADO EN LA MATERIA " + self.nom_materia2)
        if indice_materia == 3:
            if self.lista_materia3.append(un_estudiante):
                print("EL ESTUDIANTE " + un_estudiante.nombre +
                      " FUE MATRICULADO EN LA MATERIA " + self.nom_materia3)
            else:
                print("EL ESTUDIANTE " + un_estudiante.nombre +
                      " NO FUE MATRICULADO EN LA MATERIA " + self.nom_materia3)
        if indice_materia == 4:
            if self.lista_materia4.append(un_estudiante):
                print("EL ESTUDIANTE " + un_estudiante.nombre +
                      " FUE MATRICULADO EN LA MATERIA " + self.nom_materia4)
            else:
                print("EL ESTUDIANTE " + un_estudiante.nombre +
                      " NO FUE MATRICULADO EN LA MATERIA " + self.nom_materia4)

        if not self.lista.search(un_estudiante):
            self.lista.append(un_estudiante)

    def expulsar(self, pos):
        rta = " SI" if self.lista.remove(pos) else " NO"
        print("El estudiante en la posicion " + str(pos) + rta +
              " fue EXPULSADO!")

    def expulsarcod(self, data):
        rta = " SI" if self.lista.delete(Estudiante(data)) else " NO"
        rta = " SI" if self.lista_materia1.delete(Estudiante(data)) else " NO"
        print("El estudiante con codigo " + str(data) + rta +
              " fue EXPULSADO!" + self.nom_materia1)
        rta = " SI" if self.lista_materia2.delete(Estudiante(data)) else " NO"
        print("El estudiante con codigo " + str(data) + rta +
              " fue EXPULSADO!" + self.nom_materia2)
        rta = " SI" if self.lista_materia3.delete(Estudiante(data)) else " NO"
        print("El estudiante con codigo " + str(data) + rta +
              " fue EXPULSADO!" + self.nom_materia3)
        rta = " SI" if self.lista_materia4.delete(Estudiante(data)) else " NO"
        print("El estudiante con codigo " + str(data) + rta +
              " fue EXPULSADO!" + self.nom_materia4)

    def registro(self, un_estudiante):
        reg_est = self.lista.search(un_estudiante)
        if reg_est:
            print("Registro Estudiantil:")
            #print("Còdigo Nombre Nota")
            #print(" Codigo".rjust(20)+"Nombre".center(40)+"Nota".ljust(60))
            print("-" * 18)
            print(reg_est)
        else:
            print(
                f"No tenemos registrado al estudiante de còdigo {un_estudiante.codigo} en nuestras bases de datos!"
            )  # cadena formateada

    def reporte(self):
        print(f"\nColegio {self.nombre}")
        print("REPORTE DE ESTUDIANTES ACTUALMENTE MATRCULADOS")
        print("=" * 47)
        #print("Codigo Nombre Nota")
        print("-" * 18)
        self.lista.explorer()

    def reporte_por_materia(self, indice_materia):
        print(f"\n\n\nColegio {self.nombre}")
        if indice_materia == 1:
            print("REPORTE DE ESTUDIANTES ACTUALMENTE MATRCULADOS EN " +
                  self.nom_materia1)
            print("=" * 47)
            print("-" * 18)
            self.lista_materia1.explorer()
        elif indice_materia == 2:
            print("REPORTE DE ESTUDIANTES ACTUALMENTE MATRCULADOS EN " +
                  self.nom_materia2)
            print("=" * 47)
            print("-" * 18)
            self.lista_materia2.explorer()
        elif indice_materia == 3:
            print("REPORTE DE ESTUDIANTES ACTUALMENTE MATRCULADOS EN " +
                  self.nom_materia3)
            print("=" * 47)
            print("-" * 18)
            self.lista_materia3.explorer()
        elif indice_materia == 4:
            print("REPORTE DE ESTUDIANTES ACTUALMENTE MATRCULADOS EN " +
                  self.nom_materia4)
            print("=" * 47)
            print("-" * 18)
            self.lista_materia4.explorer()

    def promedio(self):
        acum = 0
        if self.lista.is_empty():
            return "No hay estudiantes MATRICULADOS para obtener el promedio"
            #input()
        else:
            for i in range(len(self.lista)):
                acum += self.lista.locate(i).nota

            prom = acum / len(self.lista)
            return "El promedio de notas de todos los estudiantes es: " + str(
                prom)

    def mayorNota(self):
        # if self.lista.is_empty():
        #     print("No hay estudiantes MATRICULADOS para obtener la mayor nota")
        #     input()
        # else:
        #     mayor_actual = self.lista.locate(0).nota
        #     for i in range(len(self.lista)):
        #         if mayor_actual < self.lista.locate(i).nota:
        #             mayor_actual=self.lista.locate(i).nota
        #     mayores_notas = SinglyLinkedList()
        #     for i in range(len(self.lista)):
        #         if mayor_actual == self.lista.locate(i).nota:
        #             mayores_notas.append(self.lista.locate(i))
        #     return "Reporte de estudiantes con mayor nota: \n" + str(mayores_notas)
        return mayorNota_Materia(self.lista)

    def mayorNota_Materia(self, lista):
        if lista.is_empty():
            print("No hay estudiantes MATRICULADOS para obtener la mayor nota")
            input()
        else:
            mayor_actual = lista.locate(0).nota
            for i in range(len(lista)):
                if mayor_actual < lista.locate(i).nota:
                    mayor_actual = lista.locate(i).nota
            mayores_notas = SinglyLinkedList()
            for i in range(len(lista)):
                if mayor_actual == lista.locate(i).nota:
                    mayores_notas.append(lista.locate(i))
            return "Reporte de estudiantes con mayor nota: \n" + str(
                mayores_notas)
Exemplo n.º 10
0
class VentanaTR(Gtk.Window):
    def __init__(self):
        super().__init__(title="Tres en Raya")
        self.connect("destroy", Gtk.main_quit)

        self.alternar = 0
        self.casillas = SinglyLinkedList()
        malla = Gtk.Grid(row_homogeneous=True, column_homogeneous=True)

        for i in range(3):
            for j in range(3):
                casilla = Gtk.Button(label="")
                casilla.connect("clicked", self.on_casilla_clicked)
                malla.attach(casilla, top=i * 2, left=j * 2, height=2, width=2)
                self.casillas.append(casilla)

        self.add(malla)

    def on_casilla_clicked(self, casilla):
        if casilla.get_label() == "":
            if self.alternar % 2 == 0:
                casilla.set_label("X")
            else:
                casilla.set_label("O")
            self.alternar += 1

        if self.hay_ganador():
            respuesta = self.mostrar_dialogo(
                "GANADOR!",
                f"Gana el juego con: {casilla.get_label()}",
                "Jugar Otra vez?",
            )

            if respuesta == Gtk.ResponseType.YES:
                self.limpiar_malla()
            elif respuesta == Gtk.ResponseType.NO:
                self.destroy()
        else:
            cnt = 0
            for i in range(len(self.casillas)):
                if self.casillas.locate(i).get_label() != "":
                    cnt += 1
            if cnt == len(self.casillas):
                respuesta = self.mostrar_dialogo("EMPATE", None,
                                                 "Jugar Otra vez?")

                if respuesta == Gtk.ResponseType.YES:
                    self.limpiar_malla()
                elif respuesta == Gtk.ResponseType.NO:
                    self.destroy()

    def mostrar_dialogo(self, titulo, text, secondary_text):
        dialog = Gtk.MessageDialog(
            parent=self,
            title=titulo,
            text=text,
            buttons=Gtk.ButtonsType.YES_NO,
            secondary_text=secondary_text,
        )
        respuesta = dialog.run()
        dialog.destroy()

        return respuesta

    def limpiar_malla(self):
        for i in range(9):
            self.casillas.locate(i).set_label("")
        self.alternar = 0

    def hay_ganador(self):
        return ((self.verificar_adyacencia(0, 1)
                 and self.verificar_adyacencia(1, 2))
                or (self.verificar_adyacencia(3, 4)
                    and self.verificar_adyacencia(4, 5))
                or (self.verificar_adyacencia(6, 7)
                    and self.verificar_adyacencia(7, 8))
                or (self.verificar_adyacencia(0, 3)
                    and self.verificar_adyacencia(3, 6))
                or (self.verificar_adyacencia(1, 4)
                    and self.verificar_adyacencia(4, 7))
                or (self.verificar_adyacencia(2, 5)
                    and self.verificar_adyacencia(5, 8))
                or (self.verificar_adyacencia(0, 4)
                    and self.verificar_adyacencia(4, 8))
                or (self.verificar_adyacencia(2, 4)
                    and self.verificar_adyacencia(4, 6)))

    def verificar_adyacencia(self, a, b):
        return (self.casillas.locate(a).get_label()
                == self.casillas.locate(b).get_label()
                and self.casillas.locate(a).get_label() != "")
Exemplo n.º 11
0
 def __init__(self) -> None:
     self.priorities = SinglyLinkedList()
     self.queues = SinglyLinkedList()
Exemplo n.º 12
0
class PriorityQueueLong:
    """
    Clase que implementa el funcionamiento del ADT Priority
    Queue, utilizando varias Queues, según el número de
    prioridades existentes. Serán atendidos, o tienen MAYOR
    prioridad, los Nodos que se encuentren en las Queues que
    manejen un valor de prioridad menor.
    """
    def __init__(self) -> None:
        self.priorities = SinglyLinkedList()
        self.queues = SinglyLinkedList()

    def is_empty(self) -> bool:
        return self.queues.is_empty() and self.priorities.is_empty()

    def enqueue(self, data: object, priority: int) -> bool:
        """
        Método que adiciona un nuevo Nodo con su dato a la Queue
        correspondiente, según la prioridad que éste tendrá.
        priority → [1 > 2 > 3 > ... > n]
        """
        if type(priority) == int and priority > 0:
            if self.is_empty():
                new_queue = Queue()
                new_queue.enqueue(data)
                return self.priorities.append(priority) and self.queues.append(
                    new_queue)
            elif type(data) == type(self.front()):
                return self.__enqueue(data, priority)
        return False

    def __enqueue(self, data: object, priority: int) -> bool:
        new_queue = Queue()
        new_queue.enqueue(data)
        size = len(self.priorities)

        if self.priorities.search(priority):
            for i in range(len(self.priorities)):
                if self.priorities.locate(i) == priority:
                    return self.queues.locate(i).enqueue(data)
        elif priority < self.priorities.locate(0):
            if self.priorities.insert(priority):
                return self.queues.insert(new_queue)
        elif priority > self.priorities.locate(size - 1):
            if self.priorities.insert(priority, size):
                return self.queues.insert(new_queue, size)
        else:
            for i in range(len(self.priorities)):
                if priority < self.priorities.locate(i):
                    return self.priorities.insert(
                        priority, i) and self.queues.insert(new_queue, i)

    def dequeue(self) -> object:
        if not self.is_empty():
            data = self.queues.locate(0).dequeue()
            if self.queues.locate(0).is_empty():
                self.queues.remove(0)
                self.priorities.remove(0)
            return data

    def front(self) -> object:
        if not self.is_empty():
            return self.queues.locate(0).front()

    def __len__(self) -> int:
        cnt = 0
        for i in self.queues:
            cnt += len(i)
        return cnt

    def __str__(self) -> str:
        acm = ""
        for i in self.queues:
            acm += str(i)
        return acm
Exemplo n.º 13
0
 def __init__(self, nombre):  # CONTRUCTOR INICIALIZA LOS ELEMENTOS BASICOS
     self.nombre = nombre
     # guardar varios estudiantes
     self.lista = SinglyLinkedList()
Exemplo n.º 14
0
class Colegio:
    def __init__(self, nombre):  # CONTRUCTOR INICIALIZA LOS ELEMENTOS BASICOS
        self.nombre = nombre
        # guardar varios estudiantes
        self.lista = SinglyLinkedList()

    def matricular(self, un_estudiante):
        """if self.lista.search(un_estudiante):
            print("estudiante encontrado")"""
        if self.lista.append(
                un_estudiante):  # con self se vincula con los metodos
            # como retorna un booleano if
            print("El estudiante llamado " + un_estudiante.nombre +
                  " FUE MATRICULADO!")
        else:
            print("El estudiante llamado " + un_estudiante.nombre +
                  " NO FUE MATRICULADO!")

    def expulsar(self, pos):
        rta = "SI" if self.lista.remove(pos) else "NO"
        print("El estudiante en la posiciòn " + str(pos) + " " + rta +
              " fue EXPULSADO!")

    """def expulsarcod(self,data):
        rta = "SI" if self.lista.delete(self.codigo)"""

    def registro(self, un_estudiante):
        reg_est = self.lista.search(un_estudiante)
        if reg_est is not None:
            print("Registro Estudiantil:")
            #print("Còdigo Nombre Nota")
            #print(" Codigo".rjust(20)+"Nombre".center(40)+"Nota".ljust(60))
            print("-" * 18)
            print(reg_est)
        else:
            print(
                f"No tenemos registrado al estudiante de còdigo {un_estudiante.codigo} en nuestras bases de datos!"
            )  # cadena formateada

    def reporte(self):
        print(f"\n\n\nColegio {self.nombre}")
        print("REPORTE DE ESTUDIANTES ACTUALMENTE MATRCULADOS")
        print("=" * 47)
        #print("Codigo Nombre Nota")
        print("-" * 18)
        self.lista.explorer()

    def promedio(self):
        acum = 0
        if self.lista.is_empty():
            return "No hay estudiantes MATRICULADOS para obtener el promedio"
            #input()
        else:
            for i in range(len(self.lista)):
                acum += self.lista.locate(i).nota

            prom = acum / len(self.lista)
            return "El promedio de notas de todos los estudiantes es: " + str(
                prom)

    def mayorNota(self):
        if self.lista.is_empty():
            print("No hay estudiantes MATRICULADOS para obtener la mayor nota")
            input()
        else:
            mayor_actual = self.lista.locate(0).nota
            for i in range(len(self.lista)):
                if mayor_actual < self.lista.locate(i).nota:
                    mayor_actual = self.lista.locate(i).nota
            mayores_notas = SinglyLinkedList()
            for i in range(len(self.lista)):
                if mayor_actual == self.lista.locate(i).nota:
                    mayores_notas.append(self.lista.locate(i))
            return "Reporte de estudiantes con mayor nota: \n" + str(
                mayores_notas)
Exemplo n.º 15
0
from adt.lists.sll import SinglyLinkedList

if __name__ == "__main__":
    sll = SinglyLinkedList()

    print("is empty:", sll.is_empty())

    print("remove 0:", sll.remove(0))
    print("remove 1:", sll.remove(1))

    print("insert 0 1:", sll.insert(0, 1))
    print(sll)

    print("is empty:", sll.is_empty())

    print("insert 0 1:", sll.insert(0, -1))
    print(sll)

    print("insert 0 1:", sll.insert(0, 0))
    print(sll)

    print("is empty:", sll.is_empty())

    for i in range(1, 10):
        sll.append(i)
    print(sll)