a = open('expressoes.txt', 'r')
i = 0
j = 0
pilhaop = []
string = []
b = a.readlines()
while j in range(len(b)):
fixa = b[j]
print b[j]
while i < len(fixa):
if fixa[i] == '^':
pilhaop.append(fixa[i])
elif fixa[i] == '*' or fixa[i] == '/' or fixa[i] == '%':
if len(pilhaop)>0 and pilhaop[-1] in '^':
string.append(pilhaop.pop())
else:
pilhaop.append(fixa[i])
elif fixa[i] == '+' or fixa[i] == '-':
if len(pilhaop)>0 and pilhaop[-1] in '* / %':
string.append(pilhaop.pop())
pilhaop.append(fixa[i])
else: #se for digito passa direto para posfixa
string.append(fixa[i])
i += 1
#esvazia a pilha
while len(pilhaop)>0:
string.append(pilhaop.pop())
print ''.join(string)
print "........................"
j += 1
我有这段代码,我试图将中缀表达式(5+3*2)从txt文件转换成后缀表达式(532*+)。代码做的是正确的,但是当我在txt文件中有多个表达式时,它是这样的:
在txt文件上:
^{pr2}$运行后:
5+3*2
532
*+
........................
6*4+8
532
*+
........................
当我打印'string'而不加入时,它显示:['5','3','2','/n','*','+']
你能帮帮我吗?在
使用strip函数删除换行符
我用这个。在我看来,它稍微减少了一些时间(O(1)vs O(n)),因为您不需要检查字符串中的每个字符,只需剪切最后一个字符。在
代码如下:
就你的情况而言:
^{pr2}$相关问题 更多 >
编程相关推荐