python计算器

功能说明:使用python编写一个计算器,实现简单的加减乘除功能。

程序的逻辑很简单,取出括号,计算里面的乘除加减,结果替换原括号内容,再循环直到最终结果。难点在于正则匹配字符和计算细节上,怎么很好协调配合并正确获得结果。



逻辑图:

wKioL1mkIB-R23yXAAC2WsM9ebY107.jpg-wh_50


程序目录:

main.py                       ###程序入口

checkstr.py                   ###字符检测

checkbrackets.py              ###字符串检测,括号切割

division_multiplication.py    ###乘除运算

addition_subtration.py        ###加减运算


主程序main.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
模拟简易计算器,用于实现简单的加减乘除功能。
这边是主程序入口
"""
from checkstr import checkstr
from checkbrackets import calculation
# mathinput:用户输入
mathinput = input("请输入需要计算的数学式子:")
_mathinput = checkstr(mathinput)
__mathinput = calculation(_mathinput)
print('--------------------------------------------------------------')
print('最后计算结果为:',__mathinput)


输入字符串检查checkstr.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-

#设置合法字符,例如1.234e-02
legalsymbol=['0','1','2','3','4','5','6','7','8','9','+','-','*','/','(',')','e','.']

#检测输入字符是否有非合法字符
def checkstr(str):
    for word in str:
        if word in legalsymbol:
            fix_str = re.sub(' ', '', str)   ###去除空格字符
            return fix_str
        else:
            print(word,"不是合法数学计算字符")
            exit()


括号检测切割checkbrackets.py 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re
from division_multiplication import division_multiplication
from addition_subtration import  addition_subtration

def calculation(cal_str):
    ###将第一个括号式子取出,计算后的结果替换原字符串中的值,再循环检测括号
    while True:
        rest = re.search('(\([\d\-\+\*\/\.]+\))', cal_str)
        ###判断是否有括号,没有括号直接进行计算
        if rest == None:
            print('没有括号,式子为:',cal_str)
            cal_str1 = division_multiplication(cal_str)
            cal_str2 = addition_subtration(cal_str1)
            print('计算结果为:',cal_str2)
            break
        ###将括号取出计算
        else:
            brackets_str=rest.group()
            print('有括号,式子为:', cal_str)
            print('取到的括号式子为:',brackets_str)
            ###计算括号内的值,再返回
            cal_str1 = division_multiplication(brackets_str)
            cal_str2 = addition_subtration(cal_str1)
            ###将结果替换第一个匹配的括号里的字符串,只替换一次
            cal_str = re.sub(r'\([\-\+\*\/\d\.e]*\)',cal_str2,cal_str,1)
            print('将括号内的式子替换后为:',cal_str)
    return cal_str2


division_multiplication.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re

def division_multiplication(input_str):
    ###判断字符是否有乘除号,没有直接返回原字符串
    if '/' not in input_str and '*' not in input_str:
        div_mul_restult=input_str
    else:
        ###将输入的字符串按['符号',‘值’]形式存放为列表
        ###([\-\+\*\/]?)取运算符号
        ###([\-\+\*\/]?)(\-?\d+\.?\d*(e\-\d*)?取数字,包括前面的负号(例:1*-1,取-1)和浮点数数学符号e,例如-6.146213e-06
        input_str = re.findall('([\-\+\*\/]?)(\-?\d+\.?\d*(e\-\d*)?)', input_str)
        div_mul_list = []
        ###循环,到所有乘除都计算完为止
        while len(input_str)!=1 :
            ###采用冒泡法,从第二个字符开始检查是否为‘/’或者‘*’,
            ### 是,进行计算,结果赋值给第一个元素,然后删乘除第二个元素
            ### 不是,将第一个列表元素移出原列表
            if input_str[1][0]=='*':
                result=float(input_str[0][1]) * float(input_str[1][1])
                input_str[0]=(input_str[0][0],str(result))
                del input_str[1]
                #print('after division_multiplication,the str is:',input_str)
            elif input_str[1][0]=='/':
                result=float(input_str[0][1]) / float(input_str[1][1])
                input_str[0]=(input_str[0][0],str(result))
                del input_str[1]
                #print('after division_multiplication,the str is:',input_str)
            else:
                ###如果第二个数字的运算符号不是乘除,将第一个数字插入到临时列表,然后在原列表中删除。
                ###注意:这里可能会有个问题,如果是1*-1,运算符可能会出错
                div_mul_list.append(input_str[0])
                del input_str[0]
                #print('go to here,div_mul_list is:',div_mul_list)
        div_mul_list.append(input_str[0])
        ###返回一个乘除法结果字符串
        div_mul_restult = ''
        for a in range(0, len(div_mul_list)):
            div_mul_restult = '%s%s%s' % (div_mul_restult, div_mul_list[a][0], div_mul_list[a][1])
    print('乘除计算后的结果为:',div_mul_restult)
    return div_mul_restult


addition_subtration.py 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# made by try
import re
def addition_subtration(input_str):
    ###将输入的字符串按['符号',‘值’]形式存放为列表
    ###([\-\+\*\/]?)取符号
    ###([\-\+\*\/]?)(\-?\d+\.?\d*(e\-\d*)?取数字,包括前面的负号(例:1--1,取-1)和浮点数数学符号e,例如-6.146213e-06
    input_str = re.findall('([\-\+\*\/]?)(\-?\d+\.?\d*(e\-\d*)?)', input_str)
    add_sub_list = []
    ###这里只计算加减,如果有乘除,则抛出异常
    for checksign in input_str:
        if checksign[0] == '/' or checksign[0] == '*':
            print('ERROR:这边是加法计算,但是有乘除运算符,计算出错!!!',checksign)
            exit()
    ###循环,到所有加减都计算完为止
    while len(input_str)!=1 :
        ###正正相加如1+4
        if input_str[0][0]=='' and input_str[1][0]=='+':
            rest = float(input_str[1][1]) + float(input_str[0][1])
            input_str[0] = ('', str(rest))
            del input_str[1]
        ###正负相加,分两种情况,1-4,4-1
        elif input_str[0][0]!='-' and input_str[1][0]=='-':
            if input_str[0][1] < input_str[1][1]:                   ###1-4
                rest = float(input_str[1][1]) - float(input_str[0][1])
                input_str[0] = ('-', str(rest))
            else:                                                   ###4-1,4-4
                rest = float(input_str[0][1]) - float(input_str[1][1])
                input_str[0] = ('', str(rest))
            del input_str[1]
        ###负负相加,-1-4
        elif input_str[0][0]=='-' and input_str[1][0]=='-':
            rest = float(input_str[1][1]) + float(input_str[0][1])
            input_str[0] = ('-', str(rest))
            del input_str[1]
        ###负正相加,分两种情况-1+4,-4+1
        elif input_str[0][0]=='-' and input_str[1][0]=='+':
            if input_str[0][1] < input_str[1][1]:                   ###-1+4
                rest = float(input_str[1][1]) - float(input_str[0][1])
                input_str[0] = ('', str(rest))
            else:                                                   ###-4+1,-4+4
                rest = float(input_str[0][1]) - float(input_str[1][1])
                input_str[0] = ('-', str(rest))
            del input_str[1]
        else:
            ###保留功能
            print('maybe something wrong!')
            exit()
    #print(input_str)
    add_sub_str = '%s%s' % (input_str[0][0], input_str[0][1])
    print('加减计算后的结果为:',add_sub_str)
    return add_sub_str


试运行:

请输入需要计算的数学式子:7+(-4*3)/5

有括号,式子为: 7+(-4*3)/5

取到的括号式子为: (-4*3)

乘除计算后的结果为: -12.0

加减计算后的结果为: -12.0

将括号内的式子替换后为: 7+-12.0/5

没有括号,式子为: 7+-12.0/5

乘除计算后的结果为: 7+-2.4

加减计算后的结果为: 4.6

计算结果为: 4.6

--------------------------------------------------------------

最后计算结果为: 4.6


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章