Exemplo n.º 1
0
def build_parse_tree(fp_exp):
    fp_list = fp_exp.split()
    p_stack = Stack()
    e_tree = BinaryTree('')
    p_stack.add(e_tree)
    current_tree = e_tree
    for i in fp_list:
        if i == '(':
            current_tree.insert_left('')
            p_stack.add(current_tree)
            current_tree = current_tree.get_left_child()
        elif i not in ['+', '-', '*', '/', ')']:
            current_tree.set_root_val(int(i))
            parent = p_stack.pop()
            current_tree = parent
        elif i in ['+', '-', '*', '/']:
            current_tree.set_root_val(i)
            current_tree.insert_right('')
            p_stack.add(current_tree)
            current_tree = current_tree.get_right_child()
        elif i == ')':
            current_tree = p_stack.pop()
        else:
            raise ValueError
    return e_tree
Exemplo n.º 2
0
 def push(self, value):
     if self._current_stack_count >= self._capacity:
         self._current_stack = Stack()
         self._stacks.push(self._current_stack)
         self._current_stack_count = 1
     else:
         self._current_stack_count += 1
     self._current_stack.push(value)
Exemplo n.º 3
0
class SortedStack(Stack):
    def __init__(self):
        super().__init__()
        self._temp = Stack()

    def push(self, value):
        if not self.is_empty():
            while not self.is_empty() and self.peek() < value:
                self._temp.push(self.pop())
        super().push(value)
        self._unload_temp()

    def _unload_temp(self):
        while not self._temp.is_empty():
            super().push(self._temp.pop())
Exemplo n.º 4
0
def loop(p):
    p += 1
    endPosition = None
    condition = []
    while listaDeTokens[p][0] != 'do':
        condition.append(listaDeTokens[p][0])
        p += 1
    conditionValue = calc(condition)
    p += 1
    i = p

    while conditionValue == "True":
        while listaDeTokens[i][0] != 'end':
            i = check(i) + 1
            conditionValue = calc(condition)

        endPosition = i
        i = p

    # caso o while inicie com condição falsa
    if endPosition == None:
        pilha_bloco = Stack()
        while listaDeTokens[p][0] != 'end' or not pilha_bloco.isEmpty():
            if listaDeTokens[p][0] == 'if' or listaDeTokens[p][
                    0] == "to" or listaDeTokens[p][0] == "while":
                pilha_bloco.push(listaDeTokens[p][0])
            elif listaDeTokens[p][0] == 'end' or listaDeTokens[p][0] == "fi":
                pilha_bloco.pop()

            p += 1
        endPosition = p

    return endPosition
Exemplo n.º 5
0
def base_converter(number, base):
    num_stack = Stack()
    values = "0123456789ABCDEFGHIJKLMOPQ"

    while number > 0:
        num_stack.add(number % base)
        number = number // base

    converted_number = ""
    while not num_stack.is_empty():
        converted_number += values[num_stack.pop()]

    return converted_number
Exemplo n.º 6
0
class SetOfStacks:
    def __init__(self, capacity: int):
        self._capacity = capacity
        self._current_stack = Stack()
        self._current_stack_count = 0
        self._stacks = Stack()
        self._stacks.push(self._current_stack)

    def push(self, value):
        if self._current_stack_count >= self._capacity:
            self._current_stack = Stack()
            self._stacks.push(self._current_stack)
            self._current_stack_count = 1
        else:
            self._current_stack_count += 1
        self._current_stack.push(value)

    def pop(self):
        if self._current_stack_count >= 1:
            self._current_stack_count -= 1
        else:
            self._current_stack = self._stacks.pop()
        return self._current_stack.dequeue()
Exemplo n.º 7
0
 def __init__(self, deck_count: int):
     i = 0
     self.piles = []
     while i < deck_count * 4:
         self.stacks[i] = Stack()
Exemplo n.º 8
0
 def __init__(self):
     super().__init__()
     self._temp = Stack()
Exemplo n.º 9
0
 def __init__(self):
     self._stack1 = Stack()
     self._stack2 = Stack()
     self._loaded = True
Exemplo n.º 10
0
class StackQueue:
    def __init__(self):
        self._stack1 = Stack()
        self._stack2 = Stack()
        self._loaded = True

    def enqueue(self, value):
        if not self._loaded:
            self._reload()
        self._stack1.push(value)

    def dequeue(self):
        if not self._loaded:
            return self._stack2.pop()
        self._unload()
        return self._stack1.pop()

    def peek(self):
        self._unload()
        value = self._stack1.peek()
        self._reload()
        return value

    def count(self):
        return self._stack1.count if self._loaded else self._stack2.count

    def _unload(self):
        while self._stack1.count > 1:
            self._stack2.push(self._stack1.pop())
        self._loaded = False

    def _reload(self):
        while self._stack2.count > 0:
            self._stack1.push(self._stack2.pop())
        self._loaded = True
Exemplo n.º 11
0
def calc(exp):
    tabela_sintatica = Singleton.instance()
    # print(exp)
    postFix = infixToPostfix(exp)
   # print(postFix)
    output = Stack()
    while len(postFix) > 0:
        if postFix[0].isnumeric():
            output.push(postFix.pop(0))

        elif postFix[0] not in ['+', '-', '*', '/', '(', ')', '>', '<', '=', '<=', '>=']:
            output.push(tabela_sintatica.tabela[postFix.pop(0)]['value'])

        else:
            v1 = output.pop()
            v2 = output.pop()
            #print(v1, v2)
            if not v1.isnumeric() or not v2.isnumeric():
                print('erro! tipo não suportado')
                exit()
            else:
                v1 = int(v1)
                v2 = int(v2)

            if postFix[0] == "+":
                output.push(str(v1+v2))
            elif postFix[0] == '-':
                output.push(str(v2-v1))
            elif postFix[0] == '*':
                output.push(str(v1*v2))
            elif postFix[0] == '/':
                
                if isinstance((v2/v1),float):
                    print('erro! tipo não suportado')
                    exit()
                    
                output.push(str(v2/v1))
            elif postFix[0] == '=':
                output.push(str(v1 == v2))
            elif postFix[0] == '<':
                output.push(str(v2 < v1))
            elif postFix[0] == '>':
                output.push(str(v2 > v1))
            elif postFix[0] == '>=':
                output.push(str(v2 >= v1))
            elif postFix[0] == '<=':
                output.push(str(v2 <= v1))
            else:
                print('erro! Operação inválida')
                exit()
            postFix.pop(0)
Exemplo n.º 12
0
def infixToPostfix(tokenList):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    prec[">"] = 0
    prec["<"] = 0
    prec["="] = 0
    prec[">="] = 0
    prec["<="] = 0

    opStack = Stack()
    postfixList = []
    for token in tokenList:
        if token.isnumeric() or token not in ['+', '-', '*', '/', '(', ')', '>', '<', '=', '<=', '>=']:
            if not token.isnumeric():
                token = tabela_sintatica.tabela[token]['value']
                if not token.isnumeric():
                    # print(postfixList)
                    print("erro! variável sem valor atribuído." + token)
                    exit()
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
                    (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return postfixList
Exemplo n.º 13
0
def infix_to_postfix(expression):
    operator_stack = Stack()
    output = []
    token_list = expression.split()
    precedence = {"^": 4, "*": 3, "/": 3, "+": 2, "-": 2, "(": 1}

    chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    for token in token_list:
        try:
            int(token)
            number = True
        except ValueError:
            number = False
        if token in chars or number:
            output.append(token)
        elif token == "(":
            operator_stack.add(token)
        elif token == ")":
            stack_token = operator_stack.pop()
            while stack_token != "(":
                output.append(stack_token)
                stack_token = operator_stack.pop()
        else:
            while (not operator_stack.is_empty()) and \
                    (precedence[operator_stack.peek()] >= precedence[token]):
                output.append(operator_stack.pop())
            operator_stack.add(token)

    while not operator_stack.is_empty():
        output.append(operator_stack.pop())

    return " ".join(output)
Exemplo n.º 14
0
 def start(cls):
     """Start a new calculation with a fresh stack."""
     cls.stack = Stack()
     return cls.stack.id_
Exemplo n.º 15
0
def condicional(p):
    p += 1
    condition = []
    while listaDeTokens[p][0] != 'then':
        condition.append(listaDeTokens[p][0])
        p += 1
    conditionValue = calc(condition)
    pilha_bloco = Stack()
    if conditionValue == "False":
        while (listaDeTokens[p][0] != 'else'
               and listaDeTokens[p][0] != 'fi') or not pilha_bloco.isEmpty():
            if listaDeTokens[p][0] == 'if' or listaDeTokens[p][
                    0] == "to" or listaDeTokens[p][0] == "while":
                pilha_bloco.push(listaDeTokens[p][0])
            elif listaDeTokens[p][0] == 'end' or listaDeTokens[p][0] == "fi":
                pilha_bloco.pop()

            p += 1

        if listaDeTokens[p][0] == 'fi':
            return p
        p += 1
    while listaDeTokens[p][0] != 'else' and listaDeTokens[p][0] != 'fi':
        p = check(p) + 1

    if listaDeTokens[p][0] != "fi":
        pilha_bloco = Stack()
        pilha_bloco.push("if")
        while not pilha_bloco.isEmpty():
            if listaDeTokens[p][0] == 'if' or listaDeTokens[p][
                    0] == "to" or listaDeTokens[p][0] == "while":
                pilha_bloco.push(listaDeTokens[p][0])
            elif listaDeTokens[p][0] == 'end' or listaDeTokens[p][0] == "fi":
                pilha_bloco.pop()

            p += 1
        p = p - 1
    return p
Exemplo n.º 16
0
 def __init__(self, capacity: int):
     self._capacity = capacity
     self._current_stack = Stack()
     self._current_stack_count = 0
     self._stacks = Stack()
     self._stacks.push(self._current_stack)
Exemplo n.º 17
0
import models.tabela_m as tabela_m
from lex import listaDeTokens
from models.stack import Stack
from models.tabela_sintatica import Singleton
import json
import sem

pilha_nt = Stack()
pilha_nt.push("$")
pilha_nt.push("programa")
tabela_sintatica = Singleton.instance()
pilha_declara = Stack()
listaDeTokens.append("$")
pilha_condicional = Stack()
fila_analise_semantica = []
p = 0


escopo = Stack()
escopo


def isTerminal(item):
    if type(item) == list:
        return True

    return (item == "op_ad" or item == "op_mul" or item == "op_atrib" or item == "id_var" or item == "id_func" or
            item == "id_proc" or item == "num" or item == "$" or item == "int" or item == "id" or item == "op_rel"
            or item == "tipo_var" or item == "tipo_func")