|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Lee-xuan 于 2020-12-10 16:56 编辑
问题在最后 两段代码有点长 恳请大佬相助!!
- #实现栈结构
- class StackUnderflow(ValueError):
- pass
- class SStack():
- def __init__(self):
- self._elems=[]
- def is_empty(self):
- return self._elems==[]
- def top(self):
- if self._elems==[]:
- raise StackUnderflow("in SStack.top()")
- return self._elems[-1]
- def push(self,elem):
- self._elems.append(elem)
- def pop(self):
- if self._elems==[]:
- raise StackUnderflow("in SStack.pop()")
- return self._elems.pop()
- #后缀表达式计算求值
- def suffix_exp_evaluator(line):
- return suffix_exp_evaluator(line.split())
- class ESStack(SStack):
- def depth(self):
- return len(self._elems)
- def suf_exp_evaluator(exp):
- operators ="+-*/"
- st=ESStack()
- for x in exp:
- if x not in operators:
- st.push(float(x))
- continue
- if st.depth()<2:
- raise SyntaxError("Short of operand(s)")
- a=st.pop()
- b=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 SyntaxError("Extra operand(s).")
- def suffix_exp_calculator():
- while True:
- try:
- line=input("Suffix Expression:")
- if line == "end":return
- res=suffix_exp_evaluator(line)
- print(res)
- except Exception as ex:
- print("Error:",type(ex),ex.args)
复制代码
以上是利用栈结构实现后缀表式的程序
- class StackUnderflow(ValueError):
- pass
- class SStack():
- def __init__(self):
- self._elems=[]
- def is_empty(self):
- return self._elems==[]
- def top(self):
- if self._elems==[]:
- raise StackUnderflow("in SStack.top()")
- return self._elems[-1]
- def push(self,elem):
- self._elems.append(elem)
- def pop(self):
- if self._elems==[]:
- raise StackUnderflow("in SStack.pop()")
- return self._elems.pop()
- def suf_exp_evaluator():
- pass
- priority={"(":1,"+":3,"-":3,"*":5,"/":5}
- infix_operators="+-*/()"
- def trans_infix_suffix(line):
- st=SStack()
- exp=[]
- for x in tokens(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()!='(':
- exp.append(st.pop())
- if st.is_empty():
- raise SyntaxError("Missing ')'.")
- st.pop()
- else:
- while (not st.is_empty and
- priority[st.pop()] >= priority[x]):
- exp.append(st.pop())
- st.push(x)
- while not st.is_empty():
- if st.top()=='(':
- raise SyntaxError("Extra '('.")
- exp.append(st.pop())
- return exp
- def test_trans_infix_suffix(s):
- print(s)
- print(trans_infix_suffix(s))
- print("Value:", suf_exp_evaluator())
- #定义生成器函数tokens
- def tokens(line):
- i,llen=0,len(line)
- while i<llen:
- while i<llen and line[i].isspace():
- i+=1
- if i>=llen:
- break
- if line[i] in infix_operators:
- yield line[i]
- i+=1
- continue
- j=i+1
- while(j<llen and not line[j].isspace() and
- line[j] not in infix_operators):
- if ((line[j]=='e' or line[j] =='E'
- and j+1< llen and line[j+1]=='-')):
- j+=1
- j+=1
- yield line[i:j]
- i=j
复制代码
以上是实现中缀表达式到后缀表达式的转换,最终完成中缀的求值
这两段代码是我照着书上实现后缀表达式的程序打的(栈结构),但程序执行后为啥没反应? |
|