def infix_to_suffix(self): op_stack = Stack() for element in self.exp_elements_infix: if element == Const.Pow or element == Const.LeftBracket: # 左括号和乘方必定入栈 op_stack.push(element) elif element == Const.Mul or element == Const.Div: # 乘除法需要弹出乘方与乘除 while op_stack.size() > 0 and \ (op_stack.peek() == Const.Mul or op_stack.peek() == Const.Div or op_stack.peek() == Const.Pow): op = op_stack.pop() self.exp_elements_suffix.append(op) op_stack.push(element) elif element == Const.Plus or element == Const.Sub: while op_stack.size() > 0 and (op_stack.peek() != Const.LeftBracket): op = op_stack.pop() self.exp_elements_suffix.append(op) op_stack.push(element) elif element == Const.RightBracket: while op_stack.peek() != Const.LeftBracket: op = op_stack.pop() self.exp_elements_suffix.append(op) op_stack.pop() else: self.exp_elements_suffix.append(element) while op_stack.size() > 0: self.exp_elements_suffix.append(op_stack.pop())
def test_peek(self): s = Stack() self.assertRaises(IndexError, s.peek) s.push(0) self.assertEqual(s.peek(), 0) s.push(1) self.assertEqual(s.peek(), 1) s.pop() self.assertNotEqual(s.peek(), 1)
def test_push(self): s = Stack() self.assertTrue(s.is_empty()) s.push('a') self.assertFalse(s.is_empty()) for i in range(50): n = random.randint(0, 1000) s.push(n) self.assertEqual(s.peek(), n)
def analize(self): check = 1 initialStack = Stack() workingStack = Stack() output = [] initialStack.push(')') initialStack.push('a') initialStack.push('+') initialStack.push('a') initialStack.push('(') initialStack.push('*') initialStack.push('a') workingStack.push(self.grammar.startingSymbol) while not initialStack.isEmpty(): print(workingStack) print(initialStack) print(self.grammar.table[(workingStack.peek(), initialStack.peek())]) if workingStack.peek() == 'e': workingStack.pop() if self.grammar.table[(workingStack.peek(), initialStack.peek())][0] == 'pop': workingStack.pop() initialStack.pop() else: if len(self.grammar.table[(workingStack.peek(), initialStack.peek())]) > 0: l = copy.deepcopy(self.grammar.table[(workingStack.peek(), initialStack.peek())][0][0]) print(l) nr = self.grammar.table[(workingStack.peek(), initialStack.peek())][0][1] print(nr) workingStack.pop() while l: workingStack.push(l[-1]) del l[-1] output.append(nr) else: check=0 print("error") break while not workingStack.isEmpty() and check == 1: output.append(self.grammar.table[(workingStack.peek(), 'e')][0][1]) workingStack.pop() print(output)