def suf_exp_evaluator(exp): operators = '+-*/' st = SStack() for x in exp: if x not in operators: st.push(x) continue if st.depth() < 2: raise ValueError a = int(st.pop()) b = int(st.pop()) if x == '+': c = b + a elif x == '-': c = b - a elif x == '*': c = b * a elif x == '/': c = b / a else: break st.push(c) if st.depth() == 1: return st.pop() raise ValueError
def check_parens(text): parents = '(){}[]' open_parents = '({[' oppsite = {')': '(', "]": '[', '}': '{'} def parentsheses(text): i, text_len = 0, len(text) while True: while i < len(text) and text[i] not in parents: i += 1 if i >= text_len: return yield text[i], i i += 1 ss = SStack() for pr, i in parentsheses(text): if pr in open_parents: ss.push(pr) elif ss.pop() != oppsite[pr]: print('匹配错误%s' % pr) return False print('匹配正确,括号正确') return True
def preorder(self): t, s = self._root, SStack() while t is not None or not s.is_empty(): while t is not None: s.push(t.right) yield t.data #此处应该有错误,没有定义过t的data属性 self._root=rootnode 作者 # 应该是认为rootnode是使用前面结点类创建的节点,那么这样就有data属性了 t = t.left t = s.pop()
def entries(self): t, s = self._root, SStack() while t is not None or not s.is_empty(): while t is not None: s.push(t) t = t.left t = s.pop() yield t.data.key, t.data.value, t = t.rignt
def maze_solve(maze, start, end): if start == end: print(start) return st = SStack() mark(maze, start) st.push((start, 0)) while not st.is_empty(): pos, nxt = st.pop() for i in range(0, 4): nexp = pos[0] + dirs[i][0], pos[1] + dirs[i][1] if nexp == end: print_path(end, pos, st) elif passable(maze, nexp): st.push((pos, i + 1)) mark(maze, pos) st.push((nexp, 0)) break print('no path')
def postorder_nonrec(t, proc): s = SStack() while t is not None or not s.is_empty(): while t is not None: # 下行,直到找到栈顶的两子数为空 s.push(t) t = t.left if t.left is not None else t.ringt # 这里不用 try,如果t下面没有子树不会报错,而是None # 看结点定义def __init__(self,dat,right=None,left=None) t = s.pop() proc(t.data) if not s.is_empty() and s.top.left == t: # 如果t是现在栈顶的左子树 t = s.top().right else: t = None #
def preorder_elements(t): s = SStack() while t is not None or not s.is_empty(): while t is not None: s.push(t.right) yield t.data t = t.left t = s.pop()
def preorder_nonrec(t, proc): s = SStack() while t is not None or not s.is_empty(): while t is not None: # 直到左枝为空 proc(t.data) s.push(t.right) t = t.left t = s.pop()
def norec_fact(n): res = 1 st = SStack() while n > 0: st.push(n) n -= 1 while not st.is_empty(): res *= st.pop() return res
def trans_infix_suffix(line): st = SStack() exp = [] for x in token(line): if x not in infix_operators: exp.append(x) elif st.is_empty() or x == '(': st.push(x) elif x == ')': while not st.is_empty() and st.top() != '(': st.append(st.pop()) if st.is_empty(): raise ValueError st.pop() else: while (not st.is_empty() and property[st.top()] >= property[x] ): # 当top是*/,x是+-的时候,将top加入 exp.append(st.pop()) st.push(x) while not st.is_empty(): if st.top() == '(': raise ValueError exp.append(st.pop()) return exp