表达式计算-Python版
来源:互联网 发布:nginx 缓存设置 编辑:程序博客网 时间:2024/05/22 02:18
运用递归的方法求解普通表达式的值
原理示意:
表达式 : 项 +或- [项] …
项 : 因子 *或/ [因子] …
因子 :表达式 或 整数(递归终点)
注: 以上类似编译原理的语法分析的巴科斯范式(BNF)表示,冒号右边能够推到出左边,也就是左边可以展开为右边的形式,知道不能再展开(遇到终结符)
index = 0def expValue(exp): global index result = termValue(exp) more = True while more: #index += 1 op = exp[index] if op in '+-': index += 1 value = termValue(exp) if op == '+': result += value else: result -= value else: more = False return resultdef factorValue(exp): global index result = 0 c = exp[index] if c == '(': index += 1 result = expValue(exp) index += 1 else: while c.isdigit(): result = 10 * result + int(c) - 0 index += 1 c = exp[index] return resultdef termValue(exp): global index result = factorValue(exp) while True: op = exp[index] if op in '*/': index += 1 value = factorValue(exp) if op == '*': result *= value else: result /= value else: break return resultdef main(): exp = '1+3*(3+1)*4+(1+5)#' result = expValue(exp) print('EXP : %d' % result) print('Compute Ok!')if __name__ == '__main__': main()
注:
1、表达式字符串最后加#字符用于判断表达式结束
2、表达式的元素之间不能用空格,可以使用类似词法分析切割表达式各个Token改进
0 0
- 表达式计算-Python版
- 解释器模式 python 表达式计算
- Python小练习:逆波兰表达式计算
- 使用Python计算逆波兰表达式
- 表达式计算(C++版)
- 用python 在c++计算数学表达式的例子
- python算法——字符串表达式的计算
- leetcode 227. basic calculator 计算字符串表达式的值 python
- 表达式计算
- 表达式计算
- 表达式计算
- 表达式计算
- 表达式计算
- 表达式计算
- 表达式计算
- 计算表达式
- 表达式计算
- 表达式计算
- linux一条命令使设备变砖
- 观察者模式
- jquery的版本共存问题
- 表面处理及喷涂01——喷砂处理
- 设计模式——适配器模式(Adapter)
- 表达式计算-Python版
- Struts2面试相关
- 要想用好ZBrush必须知道这10点
- 【b704 && BZOJ 1999】树网的核
- socket编程
- Codeforces Round #396 (Div. 2)Mahmoud and a Message
- 字符编码(unicode编码)
- 关于group by的用法 原理
- javascript重点-数据类型