实现一个可以将字符串表示的布尔表达式转化为对应的布尔值的解析器。
示例代码:
class BooleanExpressionParser:
def __init__(self, expression):
self.expression = expression
def parse(self):
# 去掉空格
expression = self.expression.replace(" ", "")
# 定义操作符优先级
operator_precedence = {"and": 2, "or": 1, "not": 3}
stack = []
output = []
# 切分表达式
tokens = []
i = 0
while i < len(expression):
token = ""
if expression[i] in ["(", ")", "and", "or", "not"]:
token = expression[i]
else:
while i < len(expression) and expression[i] not in ["(", ")", "and", "or", "not"]:
token += expression[i]
i += 1
i -= 1
tokens.append(token)
i += 1
# 将中缀表达式转换为后缀表达式
for token in tokens:
if token == "(":
stack.append(token)
elif token == ")":
while stack and stack[-1] != "(":
output.append(stack.pop())
stack.pop()
elif token in operator_precedence:
while stack and stack[-1] in operator_precedence and operator_precedence[token] <= operator_precedence[stack[-1]]:
output.append(stack.pop())
stack.append(token)
else:
output.append(token)
while stack:
output.append(stack.pop())
# 计算后缀表达式
stack = []
for token in output:
if token == "and":
val2 = stack.pop()
val1 = stack.pop()
stack.append(val1 and val2)
elif token == "or":
val2 = stack.pop()
val1 = stack.pop()
stack.append(val1 or val2)
elif token == "not":
val1 = stack.pop()
stack.append(not val1)
else:
stack.append(bool(token))
下一篇:布尔表达式仅显示错误的输出