0

我正在( (A & B) | (C & ~D) )从前端获取布尔表达式。我需要将其转换为 PyEDA 可以解决的布尔表达式。在 PyEDA 中编写布尔表达式有两个步骤。

  1. A,B,C,D = map(exprvar, "abcd") - This becomes a problem when number of boolean variables are dynamic使用或创建布尔变量 A、B、C、D A = exprvars("a", 4) - solves the dynamic variable issue but need to convert letters in the equation to A[0],A[1]...
  2. 将表达式写为( (A & B) | (C & ~D) )

尝试了以下方法。boolean_exp 表示布尔表达式字符串,num_variables 表示字符串中变量的数量。

def parse_boolean_expression(boolean_exp,num_variables):
    count = 0
    boolean_exp_list = list(boolean_exp)
    for index,char in enumerate(boolean_exp_list):
        if char.isalpha():
            boolean_exp_list[index] = "Z[{}]".format(count)
            count += 1
    final_bool_exp = "".join(boolean_exp_list)

    Z = exprvars("z", num_variables)
    expression = final_bool_exp

这种方法不起作用,因为创建的表达式和变量是字符串类型,而正确的类型应该是<class 'pyeda.boolalg.expr.OrOp'>表达式和<class 'pyeda.boolalg.expr.variables'>​​变量。

在交互模式下,我们可以轻松地完成上述步骤,但是如何在脚本模式下使用从前端发送的具有动态变量数量的布尔表达式字符串来构建这个表达式?

4

1 回答 1

0

pyEDA 具有expr()将文本转换为表达式的功能。这是它在您的示例中的工作方式。

>>> f = expr('( (A & B) | (C & ~D) )')

>>> f
Or(And(C, ~D), And(A, B))

>>> type(f)
<class 'pyeda.boolalg.expr.OrOp'>

这是更多信息的链接。
文字转表达

于 2021-01-21T20:46:31.687 回答