Python3.6实现计算器的基本功能

来源:互联网 发布:统计软件spss下载 编辑:程序博客网 时间:2024/06/08 12:09
用Python3.6实现计算器的基本功能,如:+,-,*,/,^等。 

要注意的是:输入含有括号“()”,小数点 “.”,以及使用内置的float类型会导致计算结果不够精确的问题。

基本思路是:使用逆波兰表达式算法。

代码实现:


from decimal import Decimal#将输入转化成一个列表string = input()args=list(string)#多位数被按位拆成了多个元素存在列表中,将它们重新整合成一个元素length =len(args)i=1while(i<length):    if(args[i-1]=='(' or args[i-1]==')' or args[i-1]=='+' or args[i-1]=='-' or args[i-1]=='*' or args[i-1]=='/' or args[i-1]=='^'):        i+=1        continue    if(args[i]!='(' and args[i]!=')' and args[i]!='+' and args[i]!='-' and args[i]!='*' and args[i]!='/' and args[i]!='^'):        args[i-1]+=args[i]        del args[i]        length-=1        i-=1        #碰到小数点,说明附近几个元素可以整合成一个小数        if args[i]=='.':            x=args.index('.')            args[x-1]+=args[x]            args[x-1]+=args[x+1]            del args[x]            del args[x]    i+=1#将原列表转化成逆波兰表达式列表  pri={'(':0,')':0, '+':1,'-':1, '*':2,'/':2,'^':3}stack1=[]stack2=[]for x in args:    if(x=='('):        stack1.append(x)    elif(x==')'):        top=stack1.pop()        while(top!='('):            stack2.append(top)            top=stack1.pop()    elif(x=='+' or x=='-' or x=='*' or x=='/' or x=='^'):        if(len(stack1)==0):            stack1.append(x)        else:            top1=stack1.pop()            if(pri[x]>pri[top1]):                stack1.append(top1)                stack1.append(x)            else:                while(1):                    if(pri[x]>pri[top1]):                        stack1.append(top1)                        break                    stack2.append(top1)                    if(len(stack1)==0):                        break                    top1=stack1.pop()                stack1.append(x)    else:        stack2.append(x)while(len(stack1)!=0):    stack2.append(stack1.pop())nibolan=[]stack=[]while(len(stack2)!=0):    nibolan.append(stack2.pop())#进行数学计算while(1):    top=nibolan.pop()    if(top=='+' or top=='-' or top=='*' or top=='/' or top=='^'):        y=Decimal(stack.pop())        x=Decimal(stack.pop())                if(top=='+'):            stack.append(x+y)        if(top=='-'):            stack.append(x-y)        if(top=='*'):            stack.append(x*y)        if(top=='/'):            stack.append(x/y)        if(top=='^'):            stack.append(x**y)               while(len(stack)!=0):            nibolan.append(stack.pop())    else:        stack.append(top)    if(len(nibolan)==0):        breakprint(stack[0])

解决问题的参考资料:

1.逆波兰表达式算法的介绍:点击打开链接

2.decimal模块的介绍:点击打开链接

原创粉丝点击