15. 为了帮助小学生检查口算作业,小明所在的软件开发团队计划开发一款“口算批改”App, 以提高口算批改的效率。该App 的基本设想是:将手机对着算式拍照,利用O C R(光学字符识别)技术,识别出算式,然后逐一计算,判断答案是否正确。小明分配到的任务,是要将识别得到的算式(存放在文件“equation.csv” 中,部分算式如图a所示)进行计算并返回计算结果“√”或“×”,程序运行结果如图b所示。
(1)主程序部分。
f=open("equation.csv","r") f_csv=csv.reader(f)
for row in f csv:
exp=row[0]
pos=exp.find("=")
#pos记录表达式exp中“=”的位置索引
expleft=exp[0:pos]
expright=exp[pos+1:]
print(expleft,"=",expright,end=")
lis=apart(expleft)
“自定义函数apart()将算式字符串中的数字与运算符拆解后存储在列表中返回”
if answer(lis)==int(expright):
#自定义函数answer(计算列表中算式的值)
print(" ")
else:
print("×")
该程序段采用的算法是
_______(单选,填字母:A.解析算法/B.枚举算法)
(2)拆解算式字符串中的数字与运算符,使用如下的apart()函数。从字符串中读取连续的数字组成运算数,并将其转化为整型存放在列表中,若取出的是运算符,直接以字符串型存放在列表中。请在划线处填入合适的代码。
def apart(expleft):
lis=[];t="";i=0
elen=len(expleft)
while i<elen:
if expleft[i] in "O+- *:
lis.append(expleft[i])
i+=1
else:
while i<elen and expleft[i]>="0" and expleft[i]<="9":
t+= ①
______________ i+=1
lis . append( ②
______________)
t=""
return lis
(3)算式计算使用如下的answer()函数。小明打算采用栈 这一数据结构实现对列表中算式的计算,步骤如下:
①构建操作符栈ops,构建运算数栈num;
②遍历列表中全部的运算数与运算符,若是运算数, 则运算数进栈num,若为运算符,执行③;
③I.若当前运算符为“)”,从栈 ops 中依次取出到“(”为止的全部运算符,并从栈num中取数运算;
Ⅱ.若当前运算栈为空,或者当前运算符优先级高于栈顶运算符,或者栈顶运算符为“(”,运算符进栈ops;
Ⅲ.若当前运算符优先级低于栈顶运算符,依次取出栈内优先级大于等于它的运算符并运算直到栈为空后,当前运算符进栈ops。未遍历到列表的最后一个数据,则返回②,否则执行④;
④若运算符栈中仍有运算符,依次取出运算,并将最 终的运算结果返回。
请在划线处填入合适的代码。
def
cal(nl,n2,op):
if
op=="+":return n1+n2
if
op=="-":return n1-n2
if
op=="*":return n1*n2
if
op=="/":return n1/n2
def
priority(op):
if
op in "+-":return 1
elif op
in "*/":return 2
else:return 3
def
answer(explist):
ans=0
ops,num=[],[]
#构建操作符栈ops,构建运算数栈num
for i in explist:
if type(i)==int:#若是操作数,则操作数进栈
num.append(i)
else:
if
i==")":
op=ops.pop()
while op!="(":
num2=num.pop()
num1=num.pop()
①
___________ op=ops.pop()
elif len(ops)==0 or priority(i)>priority(ops[- 1])or ops[- 1]=="(":
ops.append(i)
else:
while
len(ops)!=0
and
②
____________:
op=ops.pop()
num2=num.pop()
num1=num.pop()
num.append(cal(num1,num2,op))
ops.append(i)
while len(ops)!=0:
#若运算符栈中仍有运算符,依次取出运算
③
___________ num2=num.pop()
num1=num.pop()
num.append(cal(numl,num2,op))
ans=num[0]
return
ans