我正在尝试编写一个中缀到前缀转换器,例如我想转换这个:
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))
谁能帮我弄清楚我该如何解决这个问题。
请您参考如下方法:
我看到的带有括号子句的递归问题迫切需要递归解决方案。以下是对您的程序的重新思考,即使您不赞成我的递归论点,也可能会给您一些关于如何重构它的想法:
import sys
from enum import Enum
class Type(Enum): # This could also be done with individual classes
leftparentheses = 0
rightparentheses = 1
operator = 2
empty = 3
operand = 4
OPERATORS = { # get your data out of your code...
"+": "add",
"-": "subtract",
"*": "multiply",
"%": "modulus",
"/": "divide",
}
def textOperator(string):
if string not in OPERATORS:
sys.exit("Unknown operator: " + string)
return OPERATORS[string]
def typeof(string):
if string == '(':
return Type.leftparentheses
elif string == ')':
return Type.rightparentheses
elif string in OPERATORS:
return Type.operator
elif string == ' ':
return Type.empty
else:
return Type.operand
def process(tokens):
stack = []
while tokens:
token = tokens.pop()
category = typeof(token)
print("token = ", token, " (" + str(category) + ")")
if category == Type.operand:
stack.append(token)
elif category == Type.operator:
stack.append((textOperator(token), stack.pop(), process(tokens)))
elif category == Type.leftparentheses:
stack.append(process(tokens))
elif category == Type.rightparentheses:
return stack.pop()
elif category == Type.empty:
continue
print("stack = ", stack)
return stack.pop()
INFIX = "1 + ((C + A ) * (B - F))"
# pop/append work from right, so reverse, and require a real list
postfix = process(list(INFIX[::-1]))
print(postfix)
这个程序的结果是这样的结构:
('add', '1', ('multiply', ('add', 'C', 'A'), ('subtract', 'B', 'F')))
您应该能够将过程发布到您想要的字符串形式(同样,递归...)
PS:type 和 next 是 Python 内置和/或保留字,不要将它们用于变量名。
PPS: 将 INFIX[::-1] 替换为 sys.argv[1][::-1] 并且你可以将测试用例传递到程序中以看看它对他们做了什么。
PPPS:与您的原始版本一样,它仅处理单个数字(或单个字母变量),您需要提供比 list() 更好的分词器才能使其正常工作。
