簡體   English   中英

在布爾表達式中添加隱式括號的算法

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

這些字符串的語法可以由以下生產規則定義:

  1. S→E
  2. E→E or E
  3. E→F
  4. F→F and F
  5. F→T
  6. F→ not T
  7. T→ A
  8. T→ B
  9. T→ C
  10. T→ D

(使規則6為“ T →not T”),如果也應允許類似"not not D and not not not B"字符串。)

盡管該語法是上下文無關的,但它不是常規的 我認為您的字符串不存在常規語法,因此正則表達式不足以精確匹配這些字符串,並且通過擴展,也無法正確解析和轉換(重寫)它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM