30行代码写一个计算器,30行代码写计算器,看了70行代码的版本,咱
30行代码写一个计算器,30行代码写计算器,看了70行代码的版本,咱
看了70行代码的版本,咱也写一个基于堆栈的30行版本计算器
很简陋的,没有错误处理,也不支持变量
def calc(str): import re token=[float(y) if y[0] in '0123456789' else y for y in [x[0] for x in re.findall('(\\d+(\\.\\d+)?([eE][-+]?\\d+)?|[-+*/()])',str)]] opert,right={'+':lambda x,y:x+y,'-':lambda x,y:x-y,'*':lambda x,y:x*y,'/':lambda x,y:x/y},{'(':0,'+':1,'-':1,'*':2,'/':2,')':3} ans,stk=[],['(',] def clear(a,b,c): while c(b): x=a.pop() a[-1]=opert[b.pop()](ans[-1],x) try: for ele in token: if ele in right: {'(':lambda :stk.append(ele), ')':lambda :clear(ans,stk,lambda a:a[-1]!='(') or stk.pop(), }.get(ele,lambda : clear(ans,stk,lambda a:right[a[-1]]>=right[ele]) or stk.append(ele))() else: ans.append(ele) clear(ans,stk,lambda a:a[-1]!='(') return ans[0] except: return Noneif __name__=='__main__': while True: ans=calc(raw_input('> ')) if ans:print ' ',ans#该片段来自于http://byrx.net
相关内容
- 批量剪切图片,剪切图片,import osfro
- Python常用内置的字符串处理函数整理,python函数,收集常
- python编写的一个超级简单的密码生成器,python编写生成
- py求奇异值与特征值及其之间的关系验证,py特征值验证
- 批量生成ETL Automation APP下Perl脚本执行目录,etlperl,批量
- 使用PIL给图片加水印的工具类,pil工具类,#! /usr/bin/
- Python读取Excel的方法封装,python读取excel,今天需要从一
- PyQt4 精彩实例分析_电子钟改进版,pyqt4改进版,此代码根
- blender插件DEMO,添加一个三菱锥,blender三菱,这个blend
- 生成Chaos风格的PhotoMosaic效果,chaosphotomosaic,platform: li
评论关闭