[英]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.