[英]Algorithm to add implied parentheses in boolean expression
我有一个字符串,例如“ A和B或不是C和D”。 原子都是简单的大写字母A,B,C ...,并且运算符只是{和,或不是}。 我想设计一种算法,可以添加通常的优先级规则所隐含的括号。
谁能想到一个非常简单的方法来做到这一点? 也许使用正则表达式?
所需的输出是“(A和B)或((非C)和D)”。
可以这样简单(前面的Python代码):
def popnext(stream, token):
if stream[0:len(token)] == list(token):
del stream[0:len(token)]
return True
return False
def parse_binary(stream, operator, nextfn):
es = [nextfn(stream)]
while popnext(stream, operator):
es.append(nextfn(stream))
return '(' + ' {} '.format(operator).join(es) + ')' if len(es) > 1 else es[0]
def parse_ors(stream):
return parse_binary(stream, 'or', parse_ands)
def parse_ands(stream):
return parse_binary(stream, 'and', parse_unary)
def parse_unary(stream):
if popnext(stream, 'not'):
return '(not {})'.format(parse_unary(stream))
return parse_primary(stream)
def parse_primary(stream):
if popnext(stream, '('):
e = parse_ors(stream)
popnext(stream, ')')
return e
return stream.pop(0)
def evaluate(expression):
return parse_ors(list(expression.replace(' ', '')))[1:-1]
print evaluate('A and B or not C and D')
print evaluate('A and (B or not C) and D')
结果:
(A and B) or ((not C) and D)
A and (B or (not C)) and D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.