我正在制作一个将Prefix转换为Infix的程序,但在将括号放在表达式时遇到了问题。为了进行转换,我使用经典的堆栈算法。这是我的简单功能。
def breckets(operand1, operand2, operace):
res = ""
if (operand1.isdigit()) and (operand2.isdigit()):
res = operand1 + operace + operand2
elif (operand1.isdigit()) and (not operand2.isdigit()):
if operace == "+":
res = operand1 + operace + operand2
else:
res = operand1 + operace + "(" + operand2 + ")"
elif (not operand1.isdigit()) and (operand2.isdigit()):
if prior(operace) != 0:
res = "(" + operand1 + ")" + operace + operand2
else:
res = operand1 + operace + operand2
else:
res = "(" + operand1 + ")" + operace + "(" + operand2 + ")"
return res
def prior(a):
prior = None
if a in "+-":
prior = 0
elif a in "*/":
prior = 1
elif a in "^":
prior = 2
else:
print("Something went wrong")
exit()
return prior
但是我一定不要不必要地使用括号,任何人都可以给我一些建议吗?
这应该做:
def breckets(operand1, operand2, operace):
res = ""
if operand1.isdigit() and operand2.isdigit():
res = operand1 + operace + operand2
elif operand1.isdigit() and not operand2.isdigit():
if operace == "+":
res = operand1 + operace + operand2
else:
res = f"{operand1} {operace} ({operand2})"
elif not operand1.isdigit() and operand2.isdigit():
if prior(operace) != 0:
res = f"({operand1}) {operace} {operand2}"
else:
res = operand1 + operace + operand2
else:
res = f"{operand1}){operace}({operand2})"
return res
def prior(a):
prior = None
if a in "+-":
prior = 0
elif a in "*/":
prior = 1
elif a in "^":
prior = 2
else:
print("Something went wrong")
exit()
return prior