class Browser: def __init__(self): self.forward_stack = LinkedStack() self.back_stack = LinkedStack() def can_forward(self): return not self.forward_stack.is_empty() def can_back(self): # 容量为1时,不可后退 if self.back_stack.is_empty() or (self.back_stack.top.next is None): print("无法后退!", end="\n") return False return True def open(self, url): print("Open new url %s" % url, end="\n") self.back_stack.push(url) self.forward_stack.pop_all() def back(self): if self.can_back(): top = self.back_stack.pop() self.forward_stack.push(top) current = self.back_stack.top.data print("back to %s" % current, end="\n") def forward(self): if self.can_forward(): top = self.forward_stack.pop() self.back_stack.push(top) print("forward to %s" % top, end="\n")
def balanced_parenthese(parenthese): stack = LinkedStack() for p in parenthese: if p == '(': stack.push(p) else: if stack.is_empty(): return False stack.pop() return True if stack.is_empty() else False
def prefix_eval(expression): num_stack = LinkedStack() for e in reversed(expression): if e.isdigit(): num_stack.push(e) else: num1 = num_stack.pop() num2 = num_stack.pop() res = eval(num1 + e + num2) num_stack.push(str(res)) return num_stack.pop()
class Browser(object): """ 定义浏览器类。 """ def __init__(self): ''' 初始化。 ''' self.__stack_x = LinkedStack(5) self.__stack_y = LinkedStack(5) def open(self, url): ''' 访问新页面。 ''' print("Open new url %s" % url, end="\n") self.__stack_x.push(url) def forward(self): ''' 前进。 ''' top = self.__stack_y.pop() if top: self.__stack_x.push(top.data) print("from %s forward to %s" % (self.__stack_x.head.next.data, top.data), end="\n") else: print('can not to forward!') def back(self): ''' 后退。 ''' top = self.__stack_x.pop() if top: self.__stack_y.push(top.data) print("from %s back to %s" % (top.data, top.next.data), end="\n") else: print('can not to back!') def clear(self): ''' 清空栈。 ''' self.__stack_y.clear() def print_all(self): ''' 打印栈中所有元素。 ''' self.__stack_x.print_all() self.__stack_y.print_all()
class Evaluate: def __init__(self): self.exp = LinkedStack() def postfix_eval(self, str_exp): for i in range(0, len(str_exp)): if str_exp[i].isdigit(): self.exp.push(str_exp[i]) else: val1 = self.exp.pop() val2 = self.exp.pop() self.exp.push(str(eval(val2 + str_exp[i] + val1))) return int(self.exp.pop())
def postfix_eval(expression): num_stack = LinkedStack() for e in expression: if e.isdigit(): num_stack.push(e) else: num1 = num_stack.pop() num2 = num_stack.pop() res = eval(num2 + e + num1) num_stack.push(str(res)) return num_stack.pop()
def test_push_pop_elements(self): stack = LinkedStack() self.assertEqual(stack.count, 0) stack.push("WORST") el_from_stack = stack.pop() self.assertEqual(el_from_stack, "WORST") self.assertEqual(stack.count, 0)
def test_push_pop_thousand_elements(self): stack = LinkedStack() for idx in range(1000): stack.push("WORST BEHAVIOR") self.assertEqual(stack.count, idx + 1) for idx in range(1000): self.assertEqual(stack.count, 1000 - idx) self.assertEqual(stack.pop(), "WORST BEHAVIOR") self.assertEqual(stack.count, 0)
class Browser(): ''' 使用两个栈模拟浏览器前进后退 ''' def __init__(self): self.forward_stack = LinkedStack() self.back_stack = LinkedStack() def can_forward(self): if self.back_stack.is_empty(): return False return True def can_back(self): if self.forward_stack.is_empty(): return False return True def open(self, url): print(f"打开新地址: {url}") self.forward_stack.push(url) def back(self): if self.forward_stack.is_empty(): return top = self.forward_stack.pop() self.back_stack.push(top) print(f"后退至: {top}") def forward(self): if self.back_stack.is_empty(): return top = self.back_stack.pop() self.forward_stack.push(top) print(f"前进至: {top}")
def infix2postfix(expression): output = [] op_stack = LinkedStack() op_priority = {'*': 2, '/': 2, '%': 2, '+': 1, '-': 1, '(': 0, ')': 0} for e in expression: if e == '(': op_stack.push(e) elif e == ')': while op_stack.first() != '(': output.append(op_stack.pop()) op_stack.pop() elif e.isdigit(): output.append(e) else: while not op_stack.is_empty() and op_priority[op_stack.first()] >= op_priority[e]: output.append(op_stack.pop()) op_stack.push(e) while not op_stack.is_empty(): output.append(op_stack.pop()) return ''.join(output)
def base_convert(num, base): base_str = '0123456789ABCEDF' stack = LinkedStack() while num: rem = num % base stack.push(rem) num = num // base output = '' while not stack.is_empty(): output += base_str[stack.pop()] return output
def bracketsBalance(exp): # create new stack stk = LinkedStack() # scan across the expression for ch in exp: if ch in ['[', '(']: # push opening bracket stk.push(ch) elif ch in [']', ')']: # process closing bracket # if stack is empty or, we are at the end of stack, that means this is a floating closing bracket if stk.isEmpty(): return False # pop character from top of stack and inspect chFromStack = stk.pop() # brackets must be of same type and match up if ch == ']' and chFromStack != '[' or ch == ')' and chFromStack != '(': return False return stk.isEmpty()
def infix2prefix(expression): res_stack = LinkedStack() op_stack = LinkedStack() op_priority = {'*': 2, '/': 2, '%': 2, '+': 1, '-': 1, '(': 0, ')': 0} width = 7 if len(expression) <= 7 else len(expression) print(expression[::-1]) print('Symbol'.center(8), 'op_stack'.center(width), 'res_stack'.center(width), sep=" | ") print('-' * (width * 3 + 7)) for e in reversed(expression): if e == ')': op_stack.push(e) elif e == '(': while op_stack.first() != ')': res_stack.push(op_stack.pop()) op_stack.pop() elif e.isdigit(): res_stack.push(e) else: while op_stack.first( ) and op_priority[e] <= op_priority[op_stack.first()]: res_stack.push(op_stack.pop()) op_stack.push(e) print_stack(e, op_stack, res_stack, width) while not op_stack.is_empty(): res_stack.push(op_stack.pop()) print_stack(' ', op_stack, res_stack, width) output = '' while not res_stack.is_empty(): output += res_stack.pop() return output
def test_pop_empty_stack(self): stack = LinkedStack() with self.assertRaises(Exception): stack.pop()