鱼C论坛

 找回密码
 立即注册
查看: 2689|回复: 3

后缀表达式求值和中缀到后缀表达式的转换并中缀求值

[复制链接]
发表于 2020-12-10 16:52:25 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 Lee-xuan 于 2020-12-10 16:56 编辑

问题在最后 两段代码有点长 恳请大佬相助!!
  1. #实现栈结构                                                           
  2. class StackUnderflow(ValueError):
  3.     pass

  4. class SStack():
  5.     def __init__(self):
  6.         self._elems=[]
  7.     def is_empty(self):
  8.         return self._elems==[]
  9.     def top(self):
  10.         if self._elems==[]:
  11.             raise StackUnderflow("in SStack.top()")
  12.         return self._elems[-1]
  13.     def push(self,elem):
  14.         self._elems.append(elem)
  15.     def pop(self):
  16.         if self._elems==[]:
  17.             raise StackUnderflow("in SStack.pop()")
  18.         return self._elems.pop()

  19. #后缀表达式计算求值

  20. def suffix_exp_evaluator(line):
  21.     return suffix_exp_evaluator(line.split())
  22. class ESStack(SStack):
  23.     def depth(self):
  24.         return len(self._elems)
  25. def suf_exp_evaluator(exp):
  26.     operators ="+-*/"
  27.     st=ESStack()

  28.     for x in exp:
  29.         if x not in operators:
  30.             st.push(float(x))
  31.             continue
  32.         if st.depth()<2:
  33.             raise SyntaxError("Short of operand(s)")
  34.         a=st.pop()
  35.         b=st.pop()

  36.         if x=="+":
  37.             c=b+a
  38.         elif x=="-":
  39.             c=b-a
  40.         elif x=="*":
  41.             c=b*a
  42.         elif x=="/":
  43.             c=b/a
  44.         else:
  45.             break
  46.         st.push(c)
  47.     if st.depth()==1:
  48.         return st.pop()
  49.     raise SyntaxError("Extra operand(s).")

  50. def suffix_exp_calculator():
  51.     while True:
  52.         try:
  53.             line=input("Suffix Expression:")
  54.             if line == "end":return
  55.             res=suffix_exp_evaluator(line)
  56.             print(res)
  57.         except Exception as ex:
  58.             print("Error:",type(ex),ex.args)
复制代码


以上是利用栈结构实现后缀表式的程序

  1. class StackUnderflow(ValueError):
  2.     pass

  3. class SStack():
  4.     def __init__(self):
  5.         self._elems=[]
  6.     def is_empty(self):
  7.         return self._elems==[]
  8.     def top(self):
  9.         if self._elems==[]:
  10.             raise StackUnderflow("in SStack.top()")
  11.         return self._elems[-1]
  12.     def push(self,elem):
  13.         self._elems.append(elem)
  14.     def pop(self):
  15.         if self._elems==[]:
  16.             raise StackUnderflow("in SStack.pop()")
  17.         return self._elems.pop()

  18. def suf_exp_evaluator():
  19.     pass
  20. priority={"(":1,"+":3,"-":3,"*":5,"/":5}
  21. infix_operators="+-*/()"
  22. def trans_infix_suffix(line):
  23.     st=SStack()
  24.     exp=[]

  25.     for x in tokens(line):
  26.         if x not in infix_operators:
  27.             exp.append(x)
  28.         elif st.is_empty() or x=='(':
  29.             st.push(x)
  30.         elif x==')':
  31.             while not st.is_empty() and st.top()!='(':
  32.                 exp.append(st.pop())
  33.             if st.is_empty():
  34.                 raise SyntaxError("Missing ')'.")
  35.             st.pop()
  36.         else:
  37.             while (not st.is_empty and
  38.                    priority[st.pop()] >= priority[x]):
  39.                 exp.append(st.pop())
  40.             st.push(x)
  41.     while not st.is_empty():
  42.         if st.top()=='(':
  43.             raise SyntaxError("Extra '('.")
  44.         exp.append(st.pop())
  45.     return exp

  46. def test_trans_infix_suffix(s):
  47.     print(s)
  48.     print(trans_infix_suffix(s))
  49.     print("Value:", suf_exp_evaluator())

  50. #定义生成器函数tokens
  51. def tokens(line):
  52.     i,llen=0,len(line)
  53.     while i<llen:
  54.         while i<llen and line[i].isspace():
  55.             i+=1
  56.         if i>=llen:
  57.             break
  58.         if line[i] in infix_operators:
  59.             yield line[i]
  60.             i+=1
  61.             continue

  62.         j=i+1
  63.         while(j<llen and not line[j].isspace() and
  64.                line[j] not in infix_operators):
  65.             if ((line[j]=='e' or line[j] =='E'
  66.                    and j+1< llen and line[j+1]=='-')):
  67.                 j+=1
  68.             j+=1
  69.         yield line[i:j]
  70.         i=j
复制代码


以上是实现中缀表达式到后缀表达式的转换,最终完成中缀的求值

这两段代码是我照着书上实现后缀表达式的程序打的(栈结构),但程序执行后为啥没反应?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-12-10 23:51:39 | 显示全部楼层
上面只是定义类和函数,并没有被调用,执行没反应很正常。
另外你把原文题目发出来吧。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-12-13 22:17:23 | 显示全部楼层
suchocolate 发表于 2020-12-10 23:51
上面只是定义类和函数,并没有被调用,执行没反应很正常。
另外你把原文题目发出来吧。

1.实现栈结构
2.利用栈结构,实现后缀表达式的计算求值
3.3.实现中缀表达式到后缀表达式的转换,最终完成中缀表达式的求值
谢谢你啦
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-12-13 22:23:25 | 显示全部楼层
Lee-xuan 发表于 2020-12-13 22:17
1.实现栈结构
2.利用栈结构,实现后缀表达式的计算求值
3.3.实现中缀表达式到后缀表达式的转换,最终完 ...

请问怎么调用呢?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-30 13:02

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表