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
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)
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
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
def calc(exp): tabela_sintatica = Singleton.instance() postFix = infixToPostfix(exp) 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() 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 v1 == 0: print("Erro! Divisão por Zero") exit() if v2 % v1 != 0: print('Erro! tipo não suportado') exit() output.push(str(int(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) return output.pop()
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("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
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
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
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())
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()