我正在从前端获得一个( (A & B) | (C & ~D) )
形式的布尔表达式。我需要把它转换成一个布尔表达式,这个表达式可以通过PyEDA来解决。要在PyEDA中编写布尔表达式,需要执行两个步骤。
A,B,C,D = map(exprvar, "abcd") - This becomes a problem when number of boolean variables are dynamic
或A = exprvars("a", 4) - solves the dynamic variable issue but need to convert letters in the equation to A[0],A[1]...
创建布尔变量A、B、C、D。( (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'>
。
在交互模式中,我们可以很容易地完成上述步骤,但是如何使用包含从前端发送的动态变量的布尔表达式字符串在脚本模式下构建这个表达式呢?
发布于 2021-01-21 12:46:31
pyEDA有一个将文本转换为表达式的expr()
函数。下面是它在您的示例中的工作方式。
>>> f = expr('( (A & B) | (C & ~D) )')
>>> f
Or(And(C, ~D), And(A, B))
>>> type(f)
<class 'pyeda.boolalg.expr.OrOp'>
这是一个链接到更多的信息。
https://stackoverflow.com/questions/62690584
复制相似问题