从 and or 子句中提取所有可能的组合

问题描述 投票:0回答:1

给定的是可能组合的列表(|| 是或,&& 是和)。

lst = ['(a || b) && (c && d)', '(e && f) || (g || h)', '(i || j) || k']

我怎样才能在新列表中得到所有可能的组合? 样本的结果将是:

rsltlst = ['a && c && d', 'b && c && d',  'e && f', 'g', 'h', 'i', 'j', 'k']

谢谢!

为了降低复杂性,它也可以是单个字符串,而不是列表:

str = '(a || b) && (c && d)'

这将为您提供 2 个解决方案:

sol1 = 'a && c && d'
sol2 = 'b && c && d'
python combinations
1个回答
2
投票

您可以使用sympy。它将帮助您:

  • 使用 parse_expr
  • 解析你的表达式
  • 使用 to_dnf
  • 将表达式转换为析取范式

然后沿着

|
分开:

from sympy.parsing.sympy_parser import parse_expr
from sympy.logic.boolalg import to_dnf

lst = ['(a || b) && (c && d)', '(e && f) || (g || h)', '(i || j) || k']
lst = map(lambda x: x.replace('||', '|').replace('&&', '&'), lst)

comb = set()

for exp in lst:
    log_expr = str(to_dnf(parse_expr(exp)))
    for e in log_expr.split('|'):
        comb.add(e.strip())

print(comb)

输出:

{'k', 'g', 'i', 'h', '(a & c & d)', '(e & f)', 'j', '(b & c & d)'}
© www.soinside.com 2019 - 2024. All rights reserved.