给一个字符串,里面只会出现正整数以及 +-*/ 四种符号以及空格。已知这个字符串一定是符合算式规范的
import copy
def test(demo_str):
demo_str = demo_str.replace(' ', '')
if len(demo_str) == 1:
print(demo_str)
number = [int(demo_str[x]) for x in range(len(demo_str)) if x % 2 == 0]
suanshu = [demo_str[x] for x in range(len(demo_str)) if x % 2 == 1]
number_new = copy.deepcopy(number)
suanshu1 = copy.deepcopy(suanshu)
while True:
for i in range(len(suanshu)):
if suanshu[i] == "*":
number_new[i]=number[i] * number[i + 1]
number_new.remove(number[i + 1])
suanshu1.remove("*")
number = copy.deepcopy(number_new)
suanshu = copy.deepcopy(suanshu1)
break
if suanshu[i] == "/":
number_new[i]=number[i] // number[i + 1]
number_new.remove(number[i + 1])
suanshu1.remove("/")
number = copy.deepcopy(number_new)
suanshu = copy.deepcopy(suanshu1)
break
number = copy.deepcopy(number_new)
suanshu = copy.deepcopy(suanshu1)
if "*" not in suanshu1 and "/" not in suanshu1:
break
number_new1 = copy.deepcopy(number_new)
suanshu2 = copy.deepcopy(suanshu1)
while True:
if suanshu1[0] == "+":
number_new1[0] = number_new[0]+number_new[1]
number_new1.remove(number_new[1])
suanshu2.remove("+")
if suanshu1[0] == "-":
number_new1[0] = number_new[0]-number_new[1]
number_new1.remove(number_new[1])
suanshu2.remove("-")
number_new = copy.deepcopy(number_new1)
suanshu1=copy.deepcopy(suanshu2)
if len(suanshu2) == 0:
break
print(number_new[0])
test('1+2*3+5/5+ 8*7-5-8')