Пример #1
0
def postorder_nonrec(t, proc):
    s = SStack()
    while t is not None or not s.is_empty():
        while t is not None:  # iterate until top has no child
            s.push(t)
            t = t.left if t.left is not None else t.right
            # if we can go left, go, otherwise, go right
        t = s.pop()  # get the node to be access
        proc(t.data)
        if not s.is_empty() and s.top().left == t:
            t = s.top().right  # end of left visit, turn right
        else:
            t = None  # end of right visit, force to backtrack
Пример #2
0
def trans_infix_suffix(line):
    st = SStack()
    llen = len(line)
    exp = []
    for x in tokens(line):  # tokens 是一个待定义的生成器
        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() != "(":
                exp.append(st.pop())
            if st.is_empty():  # 没找到左括号,就是不配对
                raise SyntaxError("Missing \'(\'.")
            st.pop()  # 弹出左括号,右括号也不进栈
        else:  # 处理算术运算符,运算符都看作是左结合
            while (not st.is_empty() and priority[st.top()] >= priority[x]):
                exp.append(st.pop())
            st.push(x)  # 算术运算符进栈
    while not st.is_empty():  # 送出栈里剩下的运算符
        if st.top() == "(":  # 如果还有左括号,就是不配对
            raise SyntaxError("Extra \'(\' in expression.")
        exp.append(st.pop())
    return exp