其他分享
首页 > 其他分享> > 分配布尔逻辑表达式

分配布尔逻辑表达式

作者:互联网

我有的 :

(A.B.C) + (D.E) + (F.G.H.I)

我想要使​​用分配律:

(A + D + F).(A + D + G).(A + D + H).(A + D + I).
(A + E + F).(A + E + G).(A + E + H).(A + E + I).
(B + D + F).(B + D + G).(B + D + H).(B + D + I).
(B + E + F).(B + E + G).(B + E + H).(B + E + I).
(C + D + F).(C + D + G).(C + D + H).(C + D + I).
(C + E + F).(C + E + G).(C + E + H).(C + E + I)

这两个表达式是等效的.我使用分配定律得到第二个定律:A(B. C)⇔(A B). (A C)

该表达式可以更大,但始终由由OR分隔的AND组组成.
我正在寻找的是一个能够分发逻辑表达式的库.类似于Sympy的库,但应用于逻辑而不是代数.

解决方法:

Sympy是实现此目的的理想选择,只需看一下logic模块,尤其是Equivalentto_cnf函数,如下所示:

from sympy import *

A, B, C, D, E, F, G, H, I = symbols('A,B,C,D,E,F,G,H,I')

formula = (
    (A & B & C) | (D & E) | (F & G & H & I)
)
formula2 = (
    (A | D | F) & (A | D | G) & (A | D | H) & (A | D | I) &
    (A | E | F) & (A | E | G) & (A | E | H) & (A | E | I) &
    (B | D | F) & (B | D | G) & (B | D | H) & (B | D | I) &
    (B | E | F) & (B | E | G) & (B | E | H) & (B | E | I) &
    (C | D | F) & (C | D | G) & (C | D | H) & (C | D | I) &
    (C | E | F) & (C | E | G) & (C | E | H) & (C | E | I)
)

print(to_cnf(formula))
print(Equivalent(to_cnf(formula), formula2))

结果:

(A | D | F) & (A | D | G) & (A | D | H) & (A | D | I) & (A | E | F) & (A | E | G) & (A | E | H) & (A | E | I) & (B | D | F) & (B | D | G) & (B | D | H) & (B | D | I) & (B | E | F) & (B | E | G) & (B | E | H) & (B | E | I) & (C | D | F) & (C | D | G) & (C | D | H) & (C | D | I) & (C | E | F) & (C | E | G) & (C | E | H) & (C | E | I)
True

标签:boolean-logic,python
来源: https://codeday.me/bug/20191025/1930474.html