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


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