def delete(self, word): # If tree is empty if not self.root: return False # If trie is not empty # Put the nodes in a stack current = self.root node_stack = Stack() for char in word: if char not in current.children: return False current = current.children[char] node_stack.push(current) if not current.is_end: return False # Delete node from the end of key if node does not have children current.is_end = False for i in range(node_stack.count()): current = node_stack.pop() prev = node_stack.peek() if not current.children and prev: del prev.children[current.char] return True
def infix_to_postfix(infix): """ 中缀转后缀 :param infix:中缀表达式 :return: 后缀表达式 """ opstack = Stack() # 操作符栈 result = [] for token in infix: if is_operand(token): # 操作数 result.append(token) elif token == '(': # 遇到左括号,入栈 opstack.push(token) elif token == ')': # 遇到右括号,弹栈并将值放至result列表末尾, 直到遇到左括号 _token = opstack.pop() while _token and _token != '(': result.append(_token) _token = opstack.pop() else: # 遇到操作符,压栈,但是如果在栈中有比当前操作符优先级高的任何操作符要先弹出 while not opstack.is_empty(): top_token = opstack.peek() if higher_precedence(top_token, token): result.append(opstack.pop()) else: break opstack.push(token) while not opstack.is_empty(): result.append(opstack.pop()) return ''.join(result)
def test_peek_empty(self): mystack = Stack() result = mystack.peek() self.assertEqual(result, None) self.assertEqual(mystack.count(), 0)
def test_push(self): mystack = Stack() mystack.push('Python0') self.assertEqual(mystack.count(), 1) self.assertEqual(mystack.peek(), 'Python0')