计算器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了计算器相关的知识,希望对你有一定的参考价值。

import re
def init_compute(compute):
#输出计算式列表
compute_a = re.sub(‘ ‘,‘‘, compute)
compute_l = []
compute_list = []
for i in re.split(‘(\-\d+\.*\d*)‘,compute_a):
if i:
compute_l.append(i)
while True:
exp = compute_l.pop(0)
if len(compute_list) == 0 and re.search(‘^\-\d+\.*\d*$‘,exp):
compute_list.append(exp)
continue
if len(compute_list) != 0 :
if re.search(‘([\+\-\*\/\(]$)‘,compute_list[-1]):
compute_list.append(exp)
continue
for i in re.split(‘([\+\-\*\/\(\)])‘,exp):
if i:
compute_list.append(i)
if len(compute_l) == 0:
break
print(compute_list)
return compute_list

def is_symbol(i):
#判断是否为运算符
res = False
symbol = [‘+‘,‘-‘,‘*‘,‘/‘,‘(‘,‘)‘]
if i in symbol:
res = True
return res

def judgement(old_i,new_i):
#判断运算符优先级
level1 = [‘+‘,‘-‘]
level2 = [‘*‘,‘/‘]
level3 = [‘(‘]
level4 = [‘)‘]
if old_i in level1:
if new_i in level2 or new_i in level3:
return ‘<‘
else:
return ‘>‘
elif old_i in level2:
if new_i in level3:
return ‘<‘
else:
return ‘>‘
elif old_i in level3:
if new_i in level4:
return ‘=‘
else:
return ‘<‘


def calculate(num1,symbol,num2):
#对数字进行计算
res=0
if symbol == ‘+‘:
res = num1+num2
elif symbol == ‘-‘:
res = num1-num2
elif symbol == ‘*‘:
res = num1*num2
elif symbol == ‘/‘:
res = num1/num2
return res

def main(compute_1):
#主函数
numbers = []
symbols = []
for i in compute_1:
ret = is_symbol(i)
if ret == False : #判断列表元素是否为数字
i = float(i)
numbers.append(i)
else:
while True:
if len(symbols) == 0:
symbols.append(i)
break
res = judgement(symbols[-1],i)
if res == ‘<‘:
symbols.append(i)
break
elif res == ‘=‘:
symbols.pop()
break
elif res == ‘>‘:
symbol = symbols.pop()
num2 = numbers.pop()
num1 = numbers.pop()
numbers.append(calculate(num1, symbol, num2))

else:
while True:
if len(numbers) == 1:
break
symbol = symbols.pop()
num2 = numbers.pop()
num1 = numbers.pop()
numbers.append(calculate(num1, symbol, num2))
return numbers
def run():
print(‘示例:-1 - 2 *((-60+30+(-40/5)*(-9-2*-5/30-7/3*99/4*2998+10/-568/14))-(-4*-3)/(16-3*2))+3‘)
#-1 - 2 * (-2 + 3)
compute = input(‘请输入您要计算的公式:‘)
compute_1 = init_compute(compute)
l = main(compute_1)
print(‘计算结果:%s‘%l)

if __name__ == ‘__main__‘:
run()





以上是关于计算器的主要内容,如果未能解决你的问题,请参考以下文章

2021周岁年龄计算器,法定年龄计算器怎么用?

什么叫具有储存功能计算器?

华为荣耀5i怎么安装计算器?

计算器使用的CPU

怎么让win10自带计算器结果只显示小数而不是科学计数法

用JavaScript做一个简易的计算器