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

本文介绍了使用Python3.6实现计算器的基本功能,特别提到在处理括号、小数点和浮点数精度问题时,可以采用逆波兰表达式算法,并提供了相关模块decimal的介绍链接。
用Python3.6实现计算器的基本功能,如:+,-,*,/,^等。 

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

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

代码实现:


from decimal import Decimal

#将输入转化成一个列表
string = input()
args=list(string)

#多位数被按位拆成了多个元素存在列表中,将它们重新整合成一个元素
length =len(args)
i=1
while(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):
        break

print(stack[0])

解决问题的参考资料:

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

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值