python自動化-作業6.計算器——A
阿新 • • 發佈:2018-12-17
開發一個簡單的python計算器
實現加減乘除及拓號優先順序解析
使用者輸入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )等類似公式後,
必須自己解析裡面的(),+,-,*,/符號和公式(不能呼叫eval等類似功能偷懶實現),運算後得出結果,結果必須與真實的計算器所得出的結果一致
完成時間:2018/12/17
import re
Flog = {
'operation_flog' : None,
'unit' : {
'lift' : 0,
'right' : 0,
}
}
def basic_unit(list): # list序列的長度限定在3個元素
Flog['unit'] = {'lift':0,'right':0}
Flog['unit']['lift'] = float(list[0]) # 符號左邊的數是正數
Flog['unit']['right'] = float(list[2])
Flog['operation_flog'] = list[1]
if Flog['operation_flog'] == '/':
return float("%.2f"%(Flog['unit']['lift']/Flog['unit']['right']))
if Flog['operation_flog'] == '*':
return float("%.2f"%(Flog['unit']['lift'] * Flog['unit']['right']))
if Flog['operation_flog'] == '+':
return float("%.2f"%(Flog['unit']['lift'] + Flog['unit']['right']))
if Flog['operation_flog'] == '-':
return float("%.2f"%(Flog['unit']['lift'] - Flog['unit']['right']))
def parentheses(e):
if e.startswith('('):
tamp = re.split('\(', e)[1]
data = re.split('\)', tamp)[0]
else:
data = e
split_data = re.split(r'(\+|-)',data)
print('---{}---'.format(split_data))
for num,i in enumerate(split_data):
if i.endswith('*') or i.endswith('/'):
split_data[num] = split_data[num]+split_data[num+2]
if split_data[num-1] == '-':
split_data[num-1] = '+'
elif split_data[num-1] == '+':
split_data[num-1] = '-'
del split_data[num+2]
del split_data[num+1]
print(split_data)
while '' in split_data:
index_bit = split_data.index('')
split_data[index_bit] = split_data[index_bit+1]+split_data[index_bit+2]
del split_data[index_bit + 2]
del split_data[index_bit + 1]
print(split_data)
for num,i in enumerate(split_data): # 計算單括號內*/法
if '/' in i or '*' in i:
tamp_data = re.split(r'(\*|/)', i)
while len(tamp_data)>=3:
tamp_data[0] = basic_unit(tamp_data[0:3])
del tamp_data[2]
del tamp_data[1]
split_data[num] = tamp_data[0]
print(split_data)
while len(split_data)>=3: # 計算單括號內+-法
split_data[0] = basic_unit(split_data[0:3])
del split_data[2]
del split_data[1]
print(split_data)
return split_data[0]
if __name__ == '__main__':
while True:
in_compute_mode = input('輸入計算式(如:1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))):>>>').strip()
if ' ' in in_compute_mode:
print('輸入錯誤,請重新輸入'.center(50,'-'))
else:
while re.findall(r'\([^()]+\)',in_compute_mode):
expressions = re.search(r'\([^()]+\)',in_compute_mode).group()
v = parentheses(expressions) # 獲得括號中的計算值
data_list = in_compute_mode.split(expressions)
data_list.insert(1,str(v))
data_join = ''.join(data_list)
data_join1 = re.sub(r'\+-','-',data_join)
in_compute_mode = re.sub(r'--','+',data_join1)
print('-----------{}-----------'.format(in_compute_mode))
s = parentheses(in_compute_mode)
print('計算結果:【{}】'.format(s))