예제 #1
0
파일: queue.py 프로젝트: elreplicante/ucm
	def insertar(self, dato):
		nodo = Nodo(dato)
		nodo.siguiente = None
		if self.cabeza == 0:
	# si esta lista esta vacia, el nuevo nodo esta a la cabeza y es el ultimo
			self.cabeza = self.ultimo = nodo
		else:
	# busca el ultimo nodo
			ultimo = self.ultimo
	# agregar el nuevo nodo
			ultimo.siguiente = nodo
			self.ultimo = nodo
			self.longitud = self.longitud + 1
예제 #2
0
        imprimir(puerta)
        puerta = findCharacter(metaK._estado, visitadosDoor, colaDoor)
        findKey(door, visitadosDoor, colaDoor, metaD)
        print(makeWay(visitadosDoor, metaD))
        return makeWay(visitadosKey, metaK)


def imprimir(matriz):
    for i in range(len(matriz)):
        print(matriz[i])
    print()


ambiente = dict()
colaKey = Cola()
colaDoor = Cola()
enemigo = Enemigo()
visitadosKey = []
visitadosDoor = []
metaK = Nodo()
metaD = Nodo()
way = 0
wall = 1
key = 2
ganon = 3
door = 4
link = 5

if __name__ == "__main__":

    run()
예제 #3
0
 def __init__(self, dato):
     self.raiz = Nodo(dato)
예제 #4
0
 def agregar(self, item):
     temp = Nodo(item)
     temp.asignarSiguiente(self.cabeza)
     self.cabeza = temp
예제 #5
0
    def action_create_cfd(self, cr, uid, id, context=None):
        invoice = self.browse(cr, uid, id)[0]
        #Si ya tiene UUID no hacer nada
        if invoice.uuid:
            return True
        #Si no es el journal adecuado no hacer nada
        if invoice.company_id.cfd_mx_journal_ids:
            if invoice.journal_id.id not in [
                    x.id for x in invoice.company_id.cfd_mx_journal_ids
            ]:
                return True
        #Si es de proveedor no hacer nada
        if invoice.type.startswith("in"):
            return True
        #Si no hay terminos de pago mandar warning
        if not invoice.payment_term:
            raise osv.except_osv("Error!", "No se definio termino de pago")
        #Si no hay metodo de pago y es factura de cliente mandar warning
        if not invoice.formapago_id and not invoice.type.startswith("in"):
            raise osv.except_osv("Error!", "No se definio metodo de pago")

        version = invoice.company_id.cfd_mx_version
        test = invoice.company_id.cfd_mx_test
        dp = self.pool.get('decimal.precision').precision_get(
            cr, uid, 'Account')
        ns = version == '3.2' and 'cfdi:' or ''
        if version == '2.2':
            comprobante = Nodo(
                ns + 'Comprobante', {
                    'version':
                    '2.2',
                    'xmlns':
                    "http://www.sat.gob.mx/cfd/2",
                    'xmlns:xsi':
                    "http://www.w3.org/2001/XMLSchema-instance",
                    'xsi:schemaLocation':
                    "http://www.sat.gob.mx/cfd/2 http://www.sat.gob.mx/sitio_internet/cfd/2/cfdv22.xsd"
                })
        elif version == '3.2':
            comprobante = Nodo(
                ns + 'Comprobante', {
                    'version':
                    '3.2',
                    'xmlns:cfdi':
                    "http://www.sat.gob.mx/cfd/3",
                    'xmlns:xsi':
                    "http://www.w3.org/2001/XMLSchema-instance",
                    'xsi:schemaLocation':
                    "http://www.sat.gob.mx/cfd/3  http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv32.xsd"
                })
        else:
            raise osv.except_osv("Error!", "Versión de CFD no valida")

        if version == '2.2':
            aprobacion = self._get_aprobacion(cr, uid, id, invoice)
            comprobante.atributos.update({
                'noAprobacion': aprobacion.noAprobacion,
                'anoAprobacion': aprobacion.anoAprobacion,
                'serie': aprobacion.serie or '',
            })

        #Hora de la factura en zona horaria del usuario
        tz = self.pool.get("res.users").browse(cr, uid, uid).tz
        hora_factura_utc = datetime.now(timezone("UTC"))
        hora_factura_local = hora_factura_utc.astimezone(
            timezone(tz)).strftime("%H:%M:%S")
        print "****HORA", hora_factura_utc.strftime(
            "%H:%M:%S"), hora_factura_local, tz

        #Tipo de cambio
        #--------------
        #Si es pesos poner 1 directo
        if invoice.currency_id.name == 'MXN':
            rate = 1.0
        #Si no, obtener el tipo de cambio
        #Esto funciona aunque la moneda base no sea el peso
        else:
            model_data = self.pool.get("ir.model.data")
            mxn_rate = model_data.get_object(cr, uid, 'base', 'MXN').rate
            rate = (1.0 / invoice.currency_id.rate) * mxn_rate

        comprobante.atributos.update({
            'serie':
            invoice.journal_id.serie or '',
            'Moneda':
            invoice.currency_id.name,
            'TipoCambio':
            round(
                rate, 4
            ),  #De acuerdo al diario oficial de la federacion son 4 decimales
            'NumCtaPago':
            invoice.cuentaBanco,
            'LugarExpedicion':
            invoice.journal_id and invoice.journal_id.lugar or "",
            'metodoDePago':
            invoice.formapago_id and invoice.formapago_id.clave or "NA",
            'formaDePago':
            invoice.tipopago_id and invoice.tipopago_id.name
            or "Pago en una sola exhibicion",
            'fecha':
            str(invoice.date_invoice) + "T" + hora_factura_local,
            'folio':
            invoice.internal_number,
            'tipoDeComprobante': (invoice.type == 'out_invoice' and 'ingreso')
            or (invoice.type == 'out_refund' and 'egreso'),
            'subTotal':
            round((invoice.amount_untaxed or 0.0), dp),
            'total':
            round((invoice.amount_total or 0.0), dp),
        })
        for metodo in invoice.metodos_adicionales:
            if metodo.clave:
                comprobante.atributos["metodoDePago"] += "," + metodo.clave

        if invoice.discount:
            comprobante.atributos.update(
                {'descuento': round(invoice.discount, dp)})

        emisor = Nodo(
            ns + 'Emisor', {
                'rfc': invoice.company_id.partner_id.vat or "",
                'nombre': invoice.company_id.partner_id.name or "",
            }, comprobante)

        domicilioFiscal = Nodo(
            ns + 'DomicilioFiscal', {
                'calle':
                invoice.company_id.partner_id.street or "",
                'noExterior':
                invoice.company_id.partner_id.noExterior or "",
                'noInterior':
                invoice.company_id.partner_id.noInterior or "",
                'localidad':
                invoice.company_id.partner_id.ciudad_id
                and invoice.company_id.partner_id.ciudad_id.name or "",
                'colonia':
                invoice.company_id.partner_id.colonia_id
                and invoice.company_id.partner_id.colonia_id.name or "",
                'municipio':
                invoice.company_id.partner_id.municipio_id and
                (invoice.company_id.partner_id.municipio_id.clave_sat
                 or invoice.company_id.partner_id.municipio_id.name) or "",
                'estado':
                invoice.company_id.partner_id.state_id and
                (invoice.company_id.partner_id.state_id.code
                 or invoice.company_id.partner_id.state_id.name) or "",
                'pais':
                invoice.company_id.partner_id.country_id and
                (invoice.company_id.partner_id.country_id.code_alpha3
                 or invoice.company_id.partner_id.country_id.name) or "",
                'codigoPostal':
                invoice.company_id.partner_id.zip or "",
            }, emisor)

        regimenFiscal = Nodo(
            ns + 'RegimenFiscal', {
                'Regimen':
                invoice.company_id.partner_id.regimen_id
                and invoice.company_id.partner_id.regimen_id.name or ""
            }, emisor)

        receptor = Nodo(
            ns + 'Receptor', {
                'rfc': invoice.partner_id.vat or "",
                'nombre': invoice.partner_id.name or "",
            }, comprobante)

        domicilio = Nodo(
            ns + 'Domicilio', {
                'calle':
                invoice.partner_id.street or "",
                'noExterior':
                invoice.partner_id.noExterior or "",
                'noInterior':
                invoice.partner_id.noInterior or "",
                'localidad':
                invoice.partner_id.ciudad_id
                and invoice.partner_id.ciudad_id.name or "",
                'colonia':
                invoice.partner_id.colonia_id
                and invoice.partner_id.colonia_id.name or "",
                'municipio':
                invoice.partner_id.municipio_id and
                (invoice.partner_id.municipio_id.clave_sat
                 or invoice.partner_id.municipio_id.name) or "",
                'estado':
                invoice.partner_id.state_id and
                (invoice.partner_id.state_id.code
                 or invoice.partner_id.state_id.name) or "",
                'pais':
                invoice.partner_id.country_id and
                (invoice.partner_id.country_id.code_alpha3
                 or invoice.partner_id.country_id.name) or "",
                'codigoPostal':
                invoice.partner_id.zip or ""
            }, receptor)

        conceptos = Nodo(ns + 'Conceptos', padre=comprobante)

        impuestos_traslados = {}
        impuestos_retenidos = {}
        tasas = {}
        cfd_mx_impuestos = {}
        tax_obj = self.pool.get("account.tax")
        for line in invoice.invoice_line:
            if line.price_subtotal >= 0:
                #if line.product_id:
                #    unidad = line.product_id.uos_id and line.product_id.uos_id.name or ""
                #else:
                #    unidad = line.uos_id and line.uos_id.name or ""
                concepto = Nodo(
                    ns + 'Concepto', {
                        'descripcion':
                        line.name or "",
                        'importe':
                        round(line.price_subtotal, dp),
                        'valorUnitario':
                        round(line.price_unit, dp),
                        'cantidad':
                        round(line.quantity, dp),
                        'unidad':
                        line.uos_id and line.uos_id.name or "",
                        'noIdentificacion':
                        line.product_id and line.product_id.default_code or ""
                    }, conceptos)
                #Si está instalado el modulo de pedimentos ver si lleva pedimentos el concepto
                if self.pool.get("ir.module.module").search(
                        cr, uid, [('state', '=', 'installed'),
                                  ('name', '=', 'cfdi_pedimento')]):
                    if line.product_id.track_pedimento:
                        infoadu = Nodo(
                            ns + "InformacionAduanera", {
                                'numero':
                                line.move_id.prodlot_id.ref,
                                'fecha':
                                line.move_id.prodlot_id.fecha,
                                'aduana':
                                line.move_id.prodlot_id.aduana
                                and line.move_id.prodlot_id.aduana.name
                                or False
                            }, concepto)

            nombres_impuestos = {
                'iva': 'IVA',
                'ieps': 'IEPS',
                'iva_ret': 'IVA',
                'isr_ret': 'ISR'
            }
            #Por cada partida ver que impuestos lleva.
            #Estos impuestos tienen que tener una de las 4 categorias (iva, ieps, retencion iva, retencion isr)
            for tax in line.invoice_line_tax_id:
                if not tax.categoria:
                    raise osv.except_osv(
                        "Error",
                        "El impuesto %s no tiene categoria CFD" % tax.name)
                impuesto = nombres_impuestos[tax.categoria]
                comp = tax_obj.compute_all(cr, uid, [tax], line.price_unit,
                                           line.quantity, line.product_id,
                                           invoice.partner_id)
                importe = comp['total_included'] - comp['total']
                importe = round(importe, dp)
                if tax.type == 'percent':
                    tasas[impuesto] = round(abs(tax.amount * 100), dp)
                #Traslados
                if tax.categoria in ('iva', 'ieps'):
                    impuestos_traslados.setdefault(impuesto,
                                                   []).append(importe)
                #Retenciones
                else:
                    impuestos_retenidos.setdefault(impuesto,
                                                   []).append(importe)

        impuestos = Nodo(ns + 'Impuestos', padre=comprobante)
        retenciones = Nodo(ns + 'Retenciones', padre=impuestos)
        traslados = Nodo(ns + 'Traslados', padre=impuestos)

        totalImpuestosTrasladados = 0
        totalImpuestosRetenidos = 0
        if len(invoice.tax_line) == 0:
            traslado = Nodo(ns + 'Traslado', {
                'impuesto': 'IVA',
                'tasa': '0.00',
                'importe': '0.00'
            }, traslados)

        for impuesto in impuestos_retenidos:
            importe = abs(sum(impuestos_retenidos[impuesto]))
            Nodo(ns + 'Retencion', {
                'impuesto': impuesto,
                'importe': importe
            }, retenciones)
            totalImpuestosRetenidos += importe

        for impuesto in impuestos_traslados:
            importe = sum(impuestos_traslados[impuesto])
            Nodo(ns + 'Traslado', {
                'impuesto': impuesto,
                'importe': importe,
                'tasa': tasas[impuesto]
            }, traslados)
            totalImpuestosTrasladados += importe

        impuestos.atributos[
            'totalImpuestosTrasladados'] = totalImpuestosTrasladados
        impuestos.atributos[
            'totalImpuestosRetenidos'] = totalImpuestosRetenidos

        #Nombre largo de la moneda. Si es MXN poner 'pesos' a menos que se haya puesto algo en el campo de nombre largo
        #Si no es MXN poner lo que está en el campo de nombre largo o en su defecto el código de la moneda
        invoice.cantLetra = self.cant_letra(invoice.currency_id,
                                            invoice.amount_total)

        # *********************** Sellado del XML ************************
        xml = comprobante.toxml()
        sello, certificado, serial, cadena = self.sellar_xml(
            cr, uid, xml, invoice.company_id, version)
        comprobante.atributos.update({
            'sello': sello,
            'certificado': certificado,
            'noCertificado': serial
        })

        # ************************ Addenda *********************************
        nodo_addenda = False
        conf_addenda_obj = self.pool.get('cfd_mx.conf_addenda')
        conf_addenda_ids = conf_addenda_obj.search(
            cr, uid, [('partner_ids', 'in', invoice.partner_id.id)])
        if conf_addenda_ids:
            conf_addenda = conf_addenda_obj.browse(cr, uid,
                                                   conf_addenda_ids[0])
            addenda_obj = self.pool.get(conf_addenda.model)
            addenda = addenda_obj.create_addenda(Nodo, invoice, comprobante)
            if conf_addenda.model == "cfd_mx.addenda_detallista" or 'complemento' in conf_addenda.model:
                nom_nodo = "Complemento"
            else:
                nom_nodo = "Addenda"
            nodo_addenda = Nodo(ns + nom_nodo).append(addenda)
            addenda_obj.set_namespace(comprobante, nodo_addenda)

        # *************** Guardar XML y timbrarlo en su caso ***************
        cfd = comprobante.toxml()
        if version == '3.2':
            cfd_b64 = base64.b64encode(cfd.encode("utf-8"))
            res = self._sign_cfdi(cr, uid, invoice.company_id, cfd_b64, test)
            if res.startswith('ERROR'):
                m = re.search('text = "(.*?)"', res, re.DOTALL)
                error = m and m.group(1) or res
                raise osv.except_osv("Error", error)
            cfd = res
            uuid = re.search('UUID="(.*?)"', cfd).group(1)
            fecha_timbrado = re.search('FechaTimbrado="(.*?)"', cfd).group(1)
            sello_sat = re.search('selloSAT="(.*?)"', cfd).group(1)
            certificado_sat = re.search('noCertificadoSAT="(.*?)"',
                                        cfd).group(1)
        if nodo_addenda:
            xml_add = nodo_addenda.toxml(header=False)
            end_tag = "</" + ns + "Comprobante>"
            cfd = cfd.replace(end_tag, xml_add + end_tag)
        cfd_b64 = base64.b64encode(cfd.encode("utf-8"))
        fname = "cfd_" + invoice.number + ".xml"
        attachment_values = {
            'name': fname,
            'datas': cfd_b64,
            'datas_fname': fname,
            'description': 'Comprobante Fiscal Digital',
            'res_model': self._name,
            'res_id': invoice.id,
        }
        self.pool.get('ir.attachment').create(cr,
                                              uid,
                                              attachment_values,
                                              context=context)

        # *************** Guardar datos CFD en la base del Open ***************
        sello = re.sub("(.{100})", "\\1\n", sello, 0,
                       re.DOTALL)  #saltos de linea cada 100 caracteres
        values = {
            'hora_factura': hora_factura_local,
            'sello': sello,
            'cadena': cadena,
            'noCertificado': serial,
            'cantLetra': invoice.cantLetra,
            'tipo_cambio': rate,
        }
        if version == '2.2':
            values.update({
                'serie': aprobacion.serie,
                'noAprobacion': aprobacion.noAprobacion,
                'anoAprobacion': aprobacion.anoAprobacion
            })
        elif version == '3.2':
            values.update({
                'uuid':
                uuid.replace('-', ''),
                'serie':
                invoice.journal_id.serie or '',
                'qrcode':
                self._make_qrcode(invoice, uuid),
                'test':
                test,
                'sello_sat':
                sello_sat,
                'certificado_sat':
                certificado_sat,
                'fecha_timbrado':
                fecha_timbrado,
                'cadena_sat':
                re.sub(
                    "(.{80})", "\\1\n", '||1.0|%s|%s|%s|%s||' %
                    (uuid.lower(), fecha_timbrado, sello_sat, certificado_sat),
                    0, re.DOTALL)
            })

        self.pool.get('account.invoice').write(cr, uid, invoice.id, values)
예제 #6
0
 def agregar_ultimo(self, dato):
     if self.vacio() == True:
         self.primero = self.ultimo = Nodo(dato)
     else:
         aux = self.ultimo
         self.ultimo = aux.siguiente = Nodo(dato)
예제 #7
0
db = DB(storage)
conn = db.open()
root = conn.root()

cantidad_nodos = 0
cantidad_palabras = 0

teclas = {1: "1", 2: ("2", "a", "b", "c", "á"),
          3: ("3", "d", "e", "f", "é"),
          4: ("4", "g", "h", "i", "í"), 5: ("5", "j", "k", "l"),
          6: ("6", "m", "n", "o", "ó", "ñ"), 7: ("7", "p", "q", "r", "s"),
          8: ("8", "t", "u", "v", "ü", "ú"), 9: ("9", "w", "x", "y", "z"),
          0: "0", "#": " "}

if not 'madre' in root.keys():
    nodo_madre = Nodo()
    root['madre'] = nodo_madre
else:
    nodo_madre = root['madre']

for tecla, contenido in teclas.items():
    print tecla, contenido
    try:
        int(tecla)
    except:
        break
    try:
        if not nodo_madre.nodos[tecla]:
            nodo_madre.agregar_nodo(Nodo(), tecla)
    except:
        print "problema con tecla:", tecla
 def crear_nodo(self, nombre, padre, arista=None):
     return Nodo(nombre, padre, arista)
예제 #9
0
# prueba
from nodo import Nodo
from cluster import Cluster

nodo1 = Nodo("1kmN1234E1234")
listanombrenodos = nodo1.vecinos()
#print(listanombrenodos)
#print
#print
#listanodos1 = [nodo1]
#for kk in listanombrenodos:
#    listanodos1.append(Nodo(kk))

#for kk in listanodos1:
#    kk.dime_nombre()

cluster1 = Cluster(2)

cluster1.anadir_nodo(nodo1)
for kk in listanombrenodos:
    cluster1.anadir_nodo(Nodo(kk))

cluster1.anadir_nodo(Nodo("1kmN2222E2222"))

cluster1.imprime_nodos()
print(cluster1.lista_nodos_externos)
print(cluster1.lista_nodos_internos)

cluster1.coloca_nodos()
for kk in cluster1.lista_nodos_externos:
    print(kk.dime_nombre())
예제 #10
0
 def __init__(self, estado_inicial, estado_final):
     self.estado_final = estado_final
     self.estado_inicial = Nodo(estado_inicial)
     r = self.conseguir_ruta()
     self.enviar_ruta(r)
 def crear_nodo(self, nombre, padre, arista):
     nodo = Nodo(nombre, padre, arista)
     if padre != None:
         padre.hijos.append(nodo)
     self.nodos.append(nodo)
예제 #12
0
def main():
    #load screen
    successes, failures = pygame.init()
    screen = pygame.display.set_mode((800, 600))

    #temporizador
    clock = pygame.time.Clock()
    FPS = 120

    running = True
    #win,loose = False,False

    # INIT REFRESH RATE
    clock.tick(FPS)

    # tablero de juego
    tablero_game = Tablero()

    # position of player
    playeri = 0
    playerj = 0

    # color olbigatorio
    color_obligatorio = -1
    resalt_ob = True

    while running:
        # generar pantalla
        screen.fill((0, 0, 0))

        # dibujado
        tablero_game.show_all(screen)
        pygame.display.update()

        # mira si hay victorias
        if (tablero_game.win_condition()):
            print_title(screen, "GANA LA IA")
            running = False
            input()
            break

        ## delay
        pygame.time.delay(10)

        # show posibilities
        if (color_obligatorio != -1 and resalt_ob):
            resalt_ob = False
            coor = tablero_game.get_coor_ficha('B', color_obligatorio)
            tablero_game.resalt((coor[1], coor[0]), screen)

        #Load mouse to generathe player position
        ev = pygame.event.get()
        for event in ev:
            # handle MOUSEBUTTONUP
            if event.type == pygame.MOUSEBUTTONUP:
                pos = pygame.mouse.get_pos()
                #print(get_pos_mouse(pos))
                if (color_obligatorio == -1):
                    result = tablero_game.resalt(get_pos_mouse(pos), screen)
                elif (get_pos_mouse((pos[0], pos[1]))
                      in tablero_game.posible_option):
                    # se verifica solo el color obligartorio
                    result = tablero_game.resalt(get_pos_mouse(pos), screen)
                else:
                    coor = tablero_game.get_coor_ficha('B', color_obligatorio)
                    result = tablero_game.resalt((coor[1], coor[0]), screen)

                # dibujado
                tablero_game.show_all(screen)
                pygame.display.update()

                if (tablero_game.win_condition()):
                    print_title(screen, "GANA HUMANO")
                    running = False
                    input()
                    break

                if (result != None
                        or (tablero_game.posible_option == []
                            and tablero_game.resalt_pos[0] != None)):
                    if (tablero_game.posible_option == []
                            and tablero_game.resalt_pos[0] != None):
                        print_title(screen, "BLOQUEO")
                        print_title(screen, "HUMANO PIERDE TURNO", (605, 40),
                                    20)

                        input()
                    # se realizo la jugada y sigue la IA
                    tbtemp = copy.copy(tablero_game)
                    tbtemp.piezasK = np.copy(tablero_game.piezasK)

                    if (result == None):

                        nodoIA = Nodo("Max", color_obligatorio, 'N', 0, tbtemp)
                    else:
                        color_obligatorio = result
                        nodoIA = Nodo("Max", result, 'N', 0, tbtemp)
                        ##
                        print_title(screen, "IA PLAYING...")
                        nodoIA.get_utility()

                    # se verifica si hubo cambios en la ia
                    if (nodoIA.cambios_estado):
                        tablero_game = copy.copy(nodoIA.estado_min_max)
                        tablero_game.piezasK = np.copy(
                            nodoIA.estado_min_max.piezasK)
                        color_obligatorio = nodoIA.color_expandido

                    else:

                        print_title(screen, "BLOQUEO")
                        print_title(screen, "IA PIERDE TURNO", (605, 40), 20)
                        pygame.time.delay(200)

                    resalt_ob = True

            if event.type == pygame.QUIT:
                running = False
예제 #13
0
def findKey(goal, visitados, cola, meta):
    padre = 0
    prof = None
    _id = 0
    #Saca de la cola al nodo que ya se evaluó
    while (True):
        try:
            p = cola.quitar()
            padre = p._id
        except IndexError:
            print('Link se encuentra encerrado')
            print(info(p, cola, visitados))
            return False
        
        # condicional si encuentra la llave
        if (p._estado[p._x][p._y] == goal):
            p._estado[p._x][p._y] = link
            meta.initialState(p._x, p._y, p._padre, p._ope, p._prof, p._cost, p._id, p._estado, False)
            imprimir(meta._estado)
            info(p, cola, visitados)
            del p
            return True
        else:
            p._estado[p._x][p._y] = link
            
        # Verifica que no se salga de los limites del tablero
        # verifica si puede avanzar en las cuatro cardinalidades con el siguiente orden de prioridad:
        # up, left, down, right. Tambien busca si ya paso por este nodo, de ser asi, no agrega este camino
        # a la cola

        expand = False
        #Validaciones en cuanto a cuál dirección se mueve el nodo actual
        if (move(p._estado, p, p._x-1, p._y, goal, 'up', visitados)):
            expand = True
            p._estado[p._x][p._y] = way
            _id += 1
            n = Nodo()
            n.initialState(p._x - 1, p._y, padre, 'up', prof, 1, _id, p._estado, False)
            cola.agregar(n)
            visitados.append(n)
            del n

        if (move(p._estado, p, p._x, p._y-1, goal, 'left', visitados)):
            expand = True
            p._estado[p._x][p._y] = way
            _id += 1
            n = Nodo()
            n.initialState(p._x, p._y - 1, padre, 'left', prof, 1, _id, p._estado, False)
            cola.agregar(n)
            visitados.append(n)
            del n
        
        if (move(p._estado, p, p._x+1, p._y, goal, 'down', visitados)):
            expand = True
            p._estado[p._x][p._y] = way
            _id += 1
            n = Nodo()
            n.initialState(p._x + 1, p._y, padre, 'down', prof, 1, _id, p._estado, False)
            cola.agregar(n)
            visitados.append(n)
            del n

        if (move(p._estado, p, p._x, p._y+1, goal, 'right', visitados)):
            expand = True
            p._estado[p._x][p._y] = way
            _id += 1
            n = Nodo()
            n.initialState(p._x, p._y + 1, padre, 'right', prof, 1, _id, p._estado, False)
            cola.agregar(n)
            visitados.append(n)
            del n

        if not expand:
            p._estado[p._x][p._y] = way

        del p
예제 #14
0
 def agregar_ultimo(self,dato):
   if self.vacia() == True :
     self.cabeza = self.cola = Nodo(dato)
   else:
     aux = self.cola
     self.cola = aux.siguiente = Nodo(dato)
예제 #15
0
def findKey(goal, visitados, cola, meta):
    padre = 0
    prof = None
    _id = 0
    while (True):
        try:
            p = cola.quitar()
            padre = p._id
        except IndexError:
            print('Link se encuentra encerrado')
            print(info(p, cola, visitados))
            return False

        # condicional si encuentra la llave
        if (p._estado[p._x][p._y] == goal):
            p._estado[p._x][p._y] = link
            meta.initialState(p._x, p._y, p._padre, p._ope, p._prof, p._cost,
                              p._id, p._estado, False)
            print('Link encuentra su objetivo (llave o puerta)')
            imprimir(meta._estado)
            info(p, cola, visitados)
            del p
            return True
        else:
            p._estado[p._x][p._y] = link

        # variable para verificar si un nodo se expande o no
        expand = False

        # verificar que no se salga de los limites del tablero
        # verifica si puede avanzar en las cuatro cardinalidades con el siguiente orden de prioridad:
        # up, left, down, right. Tambien busca si ya paso por este nodo, de ser asi, no agrega este camino
        # a la cola
        if (p._x - 1 >= 0):
            # si al avanzar le estorba un enemigo, link lo mata y termina su turno
            if (p._estado[p._x - 1][p._y] == ganon):
                expand = True
                p.atacar(True)
                enemigo.morir()
                temp = copy.deepcopy(p._estado)
                temp[p._x - 1][p._y] = way
                _id += 1
                # crea un objeto tipo nodo(link) y lo agrega a la cola
                n = Nodo()
                n.initialState(p._x, p._y, padre, 'atack', p._prof, p._cost,
                               _id, temp, p._atack)
                cola.agregar(n)
                visitados.append(n)

                # eliminar variables
                del n
                del temp

            # si no encuentra un enemigo, se valida si link puede avanzar
            elif (move(p._estado, p, p._x - 1, p._y, goal, 'up', visitados)):
                # en caso de haber atacado en el turno anterior, se inhabilita el ataque
                # para que pueda avanzar
                if (p._atack):
                    p._atack = False
                expand = True
                p._estado[p._x][p._y] = way
                _id += 1
                n = Nodo()
                n.initialState(p._x - 1, p._y, padre, 'up', prof, 1, _id,
                               p._estado, False)
                cola.agregar(n)
                visitados.append(n)
                del n

        if (p._y - 1 >= 0):
            if (p._estado[p._x][p._y - 1] == ganon):
                expand = True
                p.atacar(True)
                enemigo.morir()
                temp = copy.deepcopy(p._estado)
                temp[p._x][p._y - 1] = way
                _id += 1
                n = Nodo()
                n.initialState(p._x, p._y, padre, 'atack', p._prof, p._cost,
                               _id, temp, p._atack)
                cola.agregar(n)
                visitados.append(n)

                del n
                del temp

            elif (move(p._estado, p, p._x, p._y - 1, goal, 'left', visitados)):
                if (p._atack):
                    p._atack = False
                expand = True
                p._estado[p._x][p._y] = way
                _id += 1
                n = Nodo()
                n.initialState(p._x, p._y - 1, padre, 'left', prof, 1, _id,
                               p._estado, False)
                cola.agregar(n)
                visitados.append(n)
                del n

        if (p._x + 1 < len(p._estado)):
            if (p._estado[p._x + 1][p._y] == ganon):
                expand = True
                p.atacar(True)
                enemigo.morir()
                temp = copy.deepcopy(p._estado)
                temp[p._x + 1][p._y] = way
                _id += 1
                n = Nodo()
                n.initialState(p._x, p._y, padre, 'atack', p._prof, p._cost,
                               _id, temp, p._atack)
                cola.agregar(n)
                visitados.append(n)

                del n
                del temp

            elif (move(p._estado, p, p._x + 1, p._y, goal, 'down', visitados)):
                if (p._atack):
                    p._atack = False
                expand = True
                p._estado[p._x][p._y] = way
                _id += 1
                n = Nodo()
                n.initialState(p._x + 1, p._y, padre, 'down', prof, 1, _id,
                               p._estado, False)
                cola.agregar(n)
                visitados.append(n)
                del n

        if (p._y + 1 < len(p._estado[0])):
            if (p._estado[p._x][p._y + 1] == ganon):
                expand = True
                p.atacar(True)
                enemigo.morir()
                temp = copy.deepcopy(p._estado)
                temp[p._x][p._y + 1] = way
                _id += 1
                n = Nodo()
                n.initialState(p._x, p._y, padre, 'atack', p._prof, p._cost,
                               p._id, temp, p._atack)
                cola.agregar(n)
                visitados.append(n)

                del n
                del temp

            elif (move(p._estado, p, p._x, p._y + 1, goal, 'right',
                       visitados)):
                if (p._atack):
                    p._atack = False
                expand = True
                p._estado[p._x][p._y] = way
                _id += 1
                n = Nodo()
                n.initialState(p._x, p._y + 1, padre, 'right', prof, 1, _id,
                               p._estado, False)
                cola.agregar(n)
                visitados.append(n)
                del n
        # si el nodo no se expande (no tiene salida, ya que es evitando devolverse)
        # se ubica un 0, para indicar que es una hoja del arbol
        if not expand:
            p._estado[p._x][p._y] = way

        ########## T U R N O   E N E M I G O #########

        if (enemigo._live):
            direccion = ''
            heuristica = 100
            # up
            if (enemigo._x - 1 >= 0):
                if (p._estado[enemigo._x - 1][enemigo._y]) == way:
                    up = abs(((enemigo._x - 1) - p._x) + (enemigo._y - p._x))
                    if heuristica > up:
                        heuristica = up
                        direccion = 'up'

            #left
            if (p._y - 1 >= 0):
                if (p._estado[enemigo._x][enemigo._y - 1]) == way:
                    left = abs((enemigo._x - p._x) + ((enemigo._y - 1) - p._y))
                    if heuristica > left:
                        heuristica = left
                        direccion = 'left'

            #down
            if (p._x + 1 < len(p._estado)):
                if (p._estado[enemigo._x][enemigo._y - 1]) == way:
                    down = abs(((enemigo._x + 1) - p._x) + (enemigo._y - p._y))
                    if heuristica > down:
                        heuristica = down
                        direccion = 'down'

            #right
            if (p._y + 1 < len(p._estado[0])):
                if (p._estado[enemigo._x][enemigo._y - 1]) == way:
                    right = abs((enemigo._x - p._x) + (enemigo._y -
                                                       (p._y + 1)))
                    if heuristica > right:
                        heuristica = right
                        direccion = 'right'

            if direccion == 'up':
                p._estado[enemigo._x][enemigo._y] = way
                p._estado[enemigo._x][enemigo._y - 1] = ganon
            if direccion == 'left':
                p._estado[enemigo._x][enemigo._y] = way
                p._estado[enemigo._x][enemigo._y - 1] = ganon
            if direccion == 'down':
                p._estado[enemigo._x][enemigo._y] = way
                p._estado[enemigo._x + 1][enemigo._y] = ganon
            if direccion == 'right':
                p._estado[enemigo._x][enemigo._y] = way
                p._estado[enemigo._x][enemigo._y + 1] = ganon

        del p
예제 #16
0
class DefReg:
    def __init__(self, id, s, unicoCaractere=False, expressaoPropria=False):
        self.id = id
        self.unicoCaractere = unicoCaractere
        self.expressaoPropria = expressaoPropria

        self.cadeias = []

        self.expressoes = []
        self.operacoes = []
        self.raiz = None

        inicio = 0
        i = 0
        while i < len(s):
            c = s[i]
            if c == " ":
                i += 1
                continue
            if c in ['(', ' ', ')', '*', '?', '+', '|', '[', ']']:
                if s[inicio:i] != '':
                    self.cadeias.append(s[inicio:i])
                self.cadeias.append(c)
                inicio = i + 1
            i += 1
        if s[-1] not in ['(', ' ', ')', '*', '?', '+', '|', '[', ']']:
            if s[inicio:i] != '':
                self.cadeias.append(s[inicio:i])

# ======= Referencias ===========

    def pedirRefs(self):
        return self.cadeias

    def receberRefs(self, resolucoes, nchar):
        i = 0
        r = 0
        while i < len(self.cadeias) and r < len(resolucoes):
            for k in range(nchar[i]):
                self.expressoes.append(resolucoes[r + k])
            r += nchar[i]
            i += 1

# ======= Expressoes ===========

    def forcarExpressoes(self):
        self.expressoes = self.cadeias

    def prec(self, op):
        if op == "*" or op == "?" or op == "+":
            return 2
        elif op == "|" or op == ".":
            return 1
        elif op == "|":
            return 0
        else:
            return -1

    def prepararExpressao(self):
        # explicitar concatenações
        nova_expressao = [self.expressoes[0]]
        for i in range(len(self.expressoes) - 1):
            if (self.expressoes[i] not in ['(', '*', '?', '+', '|', '[', ']'] and \
                self.expressoes[i+1] not in [ ')', '*', '?', '+', '|', '[', ']']) or \
                (self.expressoes[i] in [')', '*', '?', '+', ']'] and \
                 (self.expressoes[i+1] in ['(', '['] or isinstance(self.expressoes[i+1], DefReg))):

                nova_expressao.append(".")
            nova_expressao.append(self.expressoes[i + 1])

        self.expressoes = nova_expressao
        #print(self.expressoes)

        # transformar para prefixa
        expressoes = self.expressoes
        expressoes.reverse()
        output = []
        stack = []
        for i in expressoes:
            if isinstance(i, DefReg):
                output.append(i)
            elif i == '*' or i == "?" or i == "+":
                stack.append(i)
            elif i == "|" or i == ".":
                while len(stack) > 0 and self.prec(stack[-1]) >= self.prec(i):
                    output.append(stack.pop())
                stack.append(i)
            elif i == ')':
                stack.append(i)
            elif i == '(':
                while stack[-1] != ')':
                    output.append(stack.pop())
                stack.pop()  # parênteses
            else:
                output.append(i)
        while len(stack) > 0:
            output.append(stack.pop())
        output.reverse()
        #print("OUTPUT!")
        #print(output)
        self.operacoes = output

# ======= Arvore ===========

    def criarArvore(self):
        # retorna a raiz
        if self.unicoCaractere:
            self.raiz = Nodo(self.cadeias[0])
            return self.raiz

        self.prepararExpressao()
        operacoes = self.operacoes
        c = operacoes[0]
        index = [1]

        # crio a raiz
        raiz = Nodo(c)
        filhoEsq, filhoDir = None, None
        if isinstance(c, DefReg):
            self.raiz = c.criarArvore()
            return self.raiz
        elif c == '*' or c == '?' or c == '+':
            filhoEsq = self.avaliarNodo(1, index)
        elif c == '|' or c == '.':
            # operador binário
            filhoEsq, filhoDir = self.avaliarNodo(2, index)

        raiz.filhoEsq = filhoEsq
        raiz.filhoDir = filhoDir

        self.raiz = raiz
        return raiz

    def avaliarNodo(self, noperandos, index):
        # index é uma lista para acessarmos de qualquer nodo da árvore de recursão

        c = self.operacoes[index[0]]
        filhoEsq, filhoDir = None, None
        if isinstance(c, DefReg):
            index[0] += 1
            filhoEsq = c.criarArvore()
        elif c == '*' or c == '?' or c == '+':
            # operador unário
            index[0] += 1
            filhoEsq = self.avaliarNodo(1, index)
        elif c == '|' or c == '.':
            # operador binário
            index[0] += 1
            filhoEsq, filhoDir = self.avaliarNodo(2, index)

        nodoEsq = Nodo(c)
        if isinstance(c, DefReg):
            nodoEsq = filhoEsq  # retorna a raiz da arvore dessa definição
        else:
            nodoEsq.filhoEsq = filhoEsq
            nodoEsq.filhoDir = filhoDir

        if noperandos == 1:
            return nodoEsq

        d = self.operacoes[index[0]]
        filhoEsq, filhoDir = None, None
        if isinstance(d, DefReg):
            index[0] += 1
            filhoEsq = d.criarArvore()
        elif d == '*' or d == '?' or d == '+':
            # operador unário
            index[0] += 1
            filhoEsq = self.avaliarNodo(1, index)
        elif d == '|' or d == '.':
            # operador binário
            index[0] += 1
            filhoEsq, filhoDir = self.avaliarNodo(2, index)

        nodoDir = Nodo(d)
        if isinstance(d, DefReg):
            nodoDir = filhoEsq  # retorna a raiz da arvore dessa definição
        else:
            nodoDir.filhoEsq = filhoEsq
            nodoDir.filhoDir = filhoDir
        return nodoEsq, nodoDir

    def calcularNullable(self):
        self.raiz.calcularNullable()

    def calcularPos(self):
        dict_posicoes = {}
        self.raiz.calcularPos([1], dict_posicoes)
        return dict_posicoes

    def calcularFirstPos(self):
        self.raiz.calcularFirstPos()

    def calcularFollowPos(self, follow_pos):
        self.raiz.calcularFollowPos(follow_pos)

    # ----- print ----------

    def printarArvore(self):
        self.printarNodo(self.raiz)

    def printarNodo(self, nodo):

        if nodo.filhoEsq is None:
            fe = "/"
        else:
            fe = nodo.filhoEsq.item

        if nodo.filhoDir is None:
            fd = "/"
        else:
            fd = nodo.filhoDir.item

        if nodo.filhoEsq is not None:
            self.printarNodo(nodo.filhoEsq)

        if nodo.filhoDir is not None:
            self.printarNodo(nodo.filhoDir)

# ======= Converter AFD ===========

    def converterParaAFD(self):
        tag = DefReg('#', '#')
        tag.forcarExpressoes()
        backup = self.expressoes

        self.expressoes = ['('] + self.expressoes + [')', tag]
        raiz = self.criarArvore()
        self.calcularNullable()

        dict_posicoes = self.calcularPos()

        raiz.calcularFirstPos()
        raiz.calcularLastPos()
        follow_pos = {}
        for i in dict_posicoes:
            follow_pos[i] = set()
        self.calcularFollowPos(follow_pos)
        for i in follow_pos:
            pass

        self.expressoes = backup

        # afd
        alfabeto = set(
            [c.item for c in [dict_posicoes[i] for i in dict_posicoes]])
        alfabeto.discard('#')

        dEstados = [raiz.getFirstPos()]
        naoMarcados = [raiz.getFirstPos()]
        dTransicoes = {}

        while len(naoMarcados) > 0:
            s = naoMarcados.pop()
            for c in alfabeto:
                estadosP = [p for p in s if dict_posicoes[p].item == c]
                u = set()
                for p in estadosP:
                    u = u.union(follow_pos[p])
                if len(u) > 0:
                    if u not in dEstados:
                        dEstados.append(u)
                        naoMarcados.append(u)
                    if str(s) not in dTransicoes:
                        dTransicoes[str(s)] = {}
                    if c not in dTransicoes[str(s)]:
                        dTransicoes[str(s)][c] = {}
                    dTransicoes[str(s)][c] = str(u)
        # criar AFD
        estados = [str(e) for e in dEstados]
        estadoInicial = str(raiz.getFirstPos())
        lastPos = [p for p in raiz.getLastPos()][0]
        estadosFinais = [str(e) for e in dEstados if lastPos in e]
        afd = AFD(estados, alfabeto, estadoInicial, estadosFinais)
        # add transicoes ao AFD
        for s in dTransicoes:
            for c in dTransicoes[s]:
                afd.addTransicao(s, c, dTransicoes[s][c])
        # retornar AFD
        return afd
def get_nodi(g):
    nodi = []
    for l in range(0, g.dim):
        nodi.append(Nodo(l))
    return nodi
예제 #18
0
 def agregarElemento(self, profesor):
     nodo = Nodo(profesor)
     nodo.setSiguiente(self.__comienzo)
     self.__comienzo = nodo
     self.__actual = nodo
     self.__tope += 1
예제 #19
0
 def addNodo1(self,id,posicion,error):
     nuevo=Nodo(self.id,posicion,error)
     self.nodos.append(nuevo)
     #print("Añadido nodo",self.id,"en",posicion)
     self.id+=1
     return nuevo
예제 #20
0
def gera_nodos(lin, grafo):
    global CONTNODO
    at1 = True
    at2 = True
    rot1 = 0
    rot2 = 0
    lin[4] = lin[4][:-1]
    nodo1 = None
    nodo2 = None

    for i in grafo:
        if i.var == lin[2]:
            rot1 = i.pos
            at1 = False
        if i.var == lin[4]:
            rot2 = i.pos
            at2 = False

    if at1:
        nodo1 = Nodo()
        nodo1.pos = CONTNODO
        nodo1.var = lin[2]
        CONTNODO += 1
        grafo.append(nodo1)

    if at2:
        nodo2 = Nodo()
        nodo2.pos = CONTNODO
        nodo2.var = lin[4]
        CONTNODO += 1
        grafo.append(nodo2)

    nodotemp = Nodo()
    nodotemp.pos = CONTNODO
    nodotemp.var = lin[0]
    nodotemp.op = lin[3]
    if at1:
        nodotemp.filhos.append(nodo1.pos)
    else:
        nodotemp.filhos.append(rot1)
    if at2:
        nodotemp.filhos.append(nodo2.pos)
    else:
        nodotemp.filhos.append(rot2)
    grafo[nodotemp.filhos[0]].pai.append(CONTNODO)
    grafo[nodotemp.filhos[1]].pai.append(CONTNODO)
    CONTNODO += 1
    grafo.append(nodotemp)
예제 #21
0
 def agregar(self, val):
     if(self.raiz == None):
         self.raiz = Nodo(val)
     else:
         self.agregarNodo(val, self.raiz)
예제 #22
0
 def agregar(self, dato):
     if self.raiz is None:
         self.raiz = Nodo(dato)
     else:
         self.__agregar_recursivo(self.raiz, dato)
예제 #23
0
 def construirArbol(self, posfijo):
     posfijo.pop()
     variable = posfijo.pop()
     pilaOperador = Pila()
     for caracter in posfijo:
         if (caracter == '+' or caracter == '-' or caracter == '*'
                 or caracter == '/'):
             arbol = Nodo(caracter)
             arbol.der = pilaOperador.desapilar()
             arbol.izq = pilaOperador.desapilar()
             pilaOperador.apilar(arbol)
         else:
             arbol = Nodo(caracter)
             pilaOperador.apilar(arbol)
         self.evaluarSintaxis(arbol)
     arbol = pilaOperador.desapilar()
     self.addDiccionario(variable, self.evaluar(arbol))
     arbol1 = Nodo("=")
     arbol1.izq = arbol
     arbol1.der = Nodo(variable)
     self.evaluarSintaxis(arbol1.der)
     self.evaluarSintaxis(arbol1)
     return self.evaluar(arbol)
예제 #24
0
# Este archivo realiza la carga inicial del arbol
# previamente definido en clase.
from nodo import Nodo

nodo1 = Nodo(1, False, "( sucio, sucio, izquierda )")
nodo2 = Nodo(2, False, "( sucio, sucio, derecha )")
nodo3 = Nodo(3, False, "( limpio, sucio, izquierda )")
nodo4 = Nodo(4, False, "( limpio, sucio, derecha )")
nodo5 = Nodo(5, False, "( sucio, limpio, izquierda )")
nodo6 = Nodo(6, False, "( sucio, limpio, derecha )")
nodo7 = Nodo(7, True, "( limpio, limpio, izquierda )")
nodo8 = Nodo(8, True, "( limpio, limpio, derecha )")

# Agregamos los nodos hijo de cada nodo.
nodo1.agregaHijo(nodo3)
nodo1.agregaHijo(nodo2)
nodo2.agregaHijo(nodo6)
nodo2.agregaHijo(nodo1)
nodo3.agregaHijo(nodo4)
nodo4.agregaHijo(nodo8)
nodo4.agregaHijo(nodo3)
nodo5.agregaHijo(nodo7)
nodo5.agregaHijo(nodo6)
nodo6.agregaHijo(nodo5)
nodo7.agregaHijo(nodo8)
nodo8.agregaHijo(nodo7)

# Utilzamos un arreglo con todos los nodos del arbol
# para identificar mas rapido el estado inicial
arbol = [nodo1, nodo2, nodo3, nodo4, nodo5, nodo6, nodo7, nodo8]
예제 #25
0
파일: lista.py 프로젝트: andy10134/poo
 def agregarElemento(self, elemento):
     nodo = Nodo(elemento)
     nodo.setSiguiente(self.__comienzo)
     self.__comienzo = nodo
     self.__actual = nodo
     self.__tope += 1
예제 #26
0
    def validate_str(self, cadena, linea=0):
        lexico = self.analizador_lexico

        lexic_tokens = lexico.analizadorLexico(cadena)

        queue = [token.valor_gramatica for token in lexic_tokens]

        #print(queue)

        # Buscando errores analizador léxico
        for value in queue:
            if value == 'NoOp':  # Error operador invalido
                self.log.addError('E0', linea, cadena)
            elif value == 'NoNum':  # Error numero invalido
                self.log.addError('E1', linea, cadena)
            elif value == 'NoId':  # Error variable no declarada
                self.log.addError('E4', linea, cadena)
            elif value == 'LAMBDA' and self.main_enabled:
                self.log.addError('E3', linea, cadena)
            elif value == 'MAIN':
                self.main_enabled = True

        if (len(self.log.get_instance().errores) > 0
                or len(self.log.get_instance().warnings) > 0):
            print(self.log.get_instance())
            self.log.get_instance().errores.clear()
            self.log.get_instance().warnings.clear()
            return False

        #queue = cadena.split()

        #print (self.tokenize_array(queue))
        #print ([prod.right for prod in self.producciones])

        real_values = [str(token.palabra) for token in lexic_tokens]

        queue = lexic_tokens
        stack = list()

        stack.append(self.dolar)
        stack.append(self.nodoInicial)
        queue.append(Token(self.dolar, -1, '$', '$'))

        tabla_arbol = [['pila', 'entrada', 'operacion', 'adicionar']]

        raiz = Nodo(self.nodoInicial)
        pivote = raiz

        while (len(stack) > 0 and len(queue) > 0):
            fila_tabla = list()
            queue_vals = [token.valor_gramatica for token in queue]
            fila_tabla.append(self.tokenize_array(stack))
            fila_tabla.append(self.tokenize_array(queue_vals))
            #print('queue', [q.valor_gramatica for q in queue])
            #print('stack', stack )
            # Si queue.top es igual a stack.top()
            if queue[0].valor_gramatica == stack[-1]:
                # pop a cada estructura
                queue.pop(0)
                stack.pop()
                pivote = opera2(pivote)
                fila_tabla.append('2')  # operacion 2
                fila_tabla.append(' ')
            else:
                # pop a stack
                temp = stack.pop()
                #print('stack pop', temp)
                try:
                    # Buscar en la tabla
                    valor_tabla = self.tablaSintactica.tabla[temp][
                        queue[0].valor_gramatica]
                    tokens_vtabla = valor_tabla.split()
                    tokens_vtabla.reverse()

                    adicionar_str = ''  # adiciones al stack

                    # Visitar tabla en reversa
                    for x in tokens_vtabla:
                        # si existe cadena vacía, la metemos al stack
                        if x.strip() != 'lambda':
                            stack.append(x)
                            adicionar_str += (x + ' ')

                    if adicionar_str == '':
                        pivote = opera3(pivote)
                        fila_tabla.append('3')  # operacion 3
                        fila_tabla.append('lambda')
                    else:
                        pivote = opera1(pivote, adicionar_str.split())
                        fila_tabla.append('1')  # operacion 1

                        # Poniendo el orden de los terminales/noterminales
                        # al revés
                        reverse_adicionar = adicionar_str.split()
                        adicionar_str = ''

                        for valor in reverse_adicionar[::-1]:
                            adicionar_str += (valor + ' ')

                        fila_tabla.append(adicionar_str)

                except KeyError:
                    # Si no se encontró valor en la tabla
                    # Se halló un error de sintaxis
                    print("Error de sintaxis")
                    return False
            tabla_arbol.append(fila_tabla)

        if self.show_tree:
            for fila in tabla_arbol:
                for columna in fila:
                    print(columna.ljust(30), end=' ')
                print()

        if len(stack) == 0 and len(queue) == 0:
            self.translator.write_to_file(real_values)
            #print('Written values')

        return len(stack) == 0 and len(queue) == 0
예제 #27
0
 def addNodo(self, id, posicion, error):
     self.nodos.append(Nodo(id, posicion, error))
예제 #28
0
 def __init__(self, cantidadAristas):
     self.vertices = [Nodo(str(x)) for x in range(cantidadAristas)]
     self.aristas = []