秉着不重复造轮子,栈stack可从pythonds3包中导入,其具体的实现如下:
class Stack: """Stack implementation as a list""" def __init__(self): """Create new stack""" self._items = [] def is_empty(self): """Check if the stack is empty""" return not bool(self._items) def push(self, item): """Add an item to the stack""" self._items.append(item) def pop(self): """Remove an item from the stack""" return self._items.pop() def peek(self): """Get the value of the top item in the stack""" return self._items[-1] def size(self): """Get the number of items in the stack""" return len(self._items)
1.简单括号匹配
如:(())、((()) 括号组的检测
from pythonds3.basic import Stack def par_checker(symbol_string): s = Stack() for symbol in symbol_string: if symbol == '(': s.push(symbol) elif s.is_empty(): return False else: s.pop() if s.is_empty(): return True else: return False
2.括号匹配
from pythonds3.basic import Stack OPENS = '([{' CLOSERS = ')]}' def par_checker(symbol_string): s = Stack() for symbol in symbol_string: if symbol in OPENS: s.push(symbol) elif s.is_empty(): return False else: top = s.pop() if not match(top, symbol): return False if s.is_empty(): return True else: return False def match(op, cl): return OPENS.index(op) == CLOSERS.index(cl)
3.十进制转换为任意进制
from pythonds3.basic.stack import Stack def base_converter(dec_number, base): digits = '0123456789ABCDEF' rem_stack = Stack() while dec_number > 0: rem = dec_number % base rem_stack.push(rem) dec_number = dec_number // base num_string = '' while not rem_stack.is_empty(): num_string = num_string + digits[rem_stack.pop()] return num_string