布尔表达式删除某个元素

时间:2022-09-25 22:42:32
def parse(terms, i, ts):
s = []
while i < len(terms):
t = terms[i]
if t == '(':
if len(s):
ts.extend(s)
s = []
child, i = parse(terms, i + 1, [])
ts.append(child)
elif t == ')':
if len(s):
ts.extend(s)
return ts, i + 1
else:
s.append(terms[i])
i += 1
ts.extend(s)
return ts, i


def prune(terms, d):
ts = []
n = len(terms)
i = 0
while i < n:
if type(terms[i]) == list:
rs = prune(terms[i], d)
if not rs:
terms[i] = d
else:
ts.append(rs)
i += 1
elif terms[i] == d:
if len(ts) > 0 and ts[-1] == 'and':
ts.pop()
elif i < (n - 1) and terms[i + 1] == 'and':
i += 1
elif len(ts) > 0 and ts[-1] == 'or':
ts.pop()
elif i < (n - 1) and terms[i + 1] == 'or':
i += 1
elif len(ts) == 0 and i == (n - 1):
i += 1
i += 1
else:
ts.append(terms[i])
i += 1
return ts


def prune_all(terms, ds):
for d in ds:
terms = prune(terms, d)
return terms


def flat_terms(terms, ts):
ts.append("(")
for t in terms:
if type(t) == list:
ts.extend(flat_terms(t, []))
else:
ts.append(t)
ts.append(")")
return ts


s = "1 or ((2 and 3) and (4 or 5)) and 6"
words = [a for a in s.replace("(", " ( ").replace(")", " ) ").split(" ") if a != ""]

t, n = parse(words, 0, [])
print t
ts = prune_all(t, ['2', '3', '5'])
print " ".join(flat_terms(ts, []))