2
我正在尝试编写一个中缀到前缀转换器,例如,我想转换此:将中缀转换为python中的前缀
1 + ((C + A) * (B - F))
喜欢的东西:
add(1, multiply(add(C, A), subtract(B, F)))
,但我得到这个代替:
multiply(add(1, add(C, A), subtract(B, F)))
这是我的代码到目前为止
postfix = []
temp = []
newTemp = []
def textOperator(s):
if s is '+':
return 'add('
elif s is '-':
return 'subtract('
elif s is '*':
return 'multiply('
else:
return ""
def typeof(s):
if s is '(':
return leftparentheses
elif s is ')':
return rightparentheses
elif s is '+' or s is '-' or s is '*' or s is '%' or s is '/':
return operator
elif s is ' ':
return empty
else :
return operand
infix = "1 + ((C + A) * (B - F))"
for i in infix :
type = typeof(i)
if type is operand:
newTemp.append(i)
elif type is operator:
postfix.append(textOperator(i))
postfix.append(newTemp.pop())
postfix.append(', ')
elif type is leftparentheses :
newTemp.append(i)
elif type is rightparentheses :
next = newTemp.pop()
while next is not '(':
postfix.append(next)
next = newTemp.pop()
postfix.append(')')
newTemp.append(''.join(postfix))
while len(postfix) > 0 :
postfix.pop()
elif type is empty:
continue
print("newTemp = ", newTemp)
print("postfix = ", postfix)
while len(newTemp) > 0 :
postfix.append(newTemp.pop())
postfix.append(')')
print(''.join(postfix))
有人可以帮我弄清楚我会解决这个问题。
一般评论:不要使用'is',而应使用'=='。 '=='通过值进行比较,而'is'通过身份进行比较。两个字符串可以具有相同的值,但不是*相同的身份。请参阅:[为什么使用'=='或'is'来比较Python中的字符串有时会产生不同的结果?](http://stackoverflow.com/q/1504717/660921)。 – Carpetsmoker