【问题标题】:Convert formula to cnf python将公式转换为cnf python
【发布时间】:2018-12-15 17:43:04
【问题描述】:

我想将公式转换为 CNF。有图书馆可以做到这一点吗?这是我的代码。我创建了许多函数来将任何(a 或 b)转换为 CNF 格式。

但是如果有很多命题,那就很难像 (a > b) & (c & d) or not(f) ..

operator="&|>=~"

def isOperand(c):
    return c >= 'a' and c <= 'z'

operators ="&|>=~"
def isOperator(c): #it cheak if the the given c is on the operators
 return c in operators
def dblimplique(a):
    if(a=='a = b' ):
       a='(a > b) & (b > a)'
    return a
def limplique(a):
    if(a=='a > b' ):
       a='~a | b'
    return a
def nonAouB(a):
    if(a=='~(a | b)' ):
       a='~a & ~b'
    return a
def nonAetB(a):
    if (a == '~(a & b)'):
        a = '~a | ~b'
    return a
def doublenon(a):
    if (a == '~~a'):
        a = 'a'
    return a
def doublenon(a):
    if (a == '~~a'):
        a = 'a'
    return a
def AetBouc(a):
    if (a == 'a & (b | c)'):
        a = '(a & b) | (a & c)'
    return a


def AouBetc(a):
    if (a == 'a | (b & c)'):
        a = '(a | b) & (a | c)'
    return a


def FNC():
    input_string = input("Entrer votre formule:")
    if(input_string == 'a = b'):
           return dblimplique(input_string)

    elif(input_string=='a > b'):
            return limplique(input_string)

    elif(input_string=='~(a | b)'):
            return  nonAouB(input_string)

    elif(input_string == '~(a & b)'):
            return nonAetB(input_string)

    elif(input_string =='~~a'):
            return  doublenon(input_string)
    elif(input_string =='a & (b | c)'):
        return AetBouc(input_string)
    elif(input_string=='a | (b & c)'):
        return AouBetc(input_string)
    elif(input_string=='a | b' or 'a | b | c' or 'a | b | c | d' or 'a | b | c | d'):
        return input_string
    else:
      for i in input_string:
          if(i == 'a > b' or 'c > d' or 'e > f'):
              return limplique(i)


print(FNC())

【问题讨论】:

  • 如果您将公式拆分为基本部分,例如x OPERAND y,您可以大大简化您的代码。如果您无法解决这个问题,您可能需要重新编写您的问题。 (请不要只添加“好的,那我该怎么做?”这会使您的问题过于宽泛。).. 一些示例输入和输出也很好。

标签: python python-3.x logical-operators boolean-logic cnf


【解决方案1】:

使用这个模块pip install sympy

from sympy.logic.boolalg import to_cnf
from sympy.abc import A, B, D
to_cnf(~(A | B) | D)

这是一个很好的图书馆:https://docs.sympy.org/latest/modules/logic.html

这是两个代码: https://github.com/ldkrsi/cnf_py

https://github.com/omkarkarande/CNF-Converter

【讨论】:

  • 非常感谢,但是 to_cnf 中 Equivalent 的符号是什么
  • @YacineBenatia 你的意思是to_nnf(Equivalent(A &gt;&gt; B, B &gt;&gt; A))
  • 我的意思是 Equivalent 的符号,例如 (A 和 B) 它是 & 和 (A 或 B) 或否定它是 ~ 但是对于 Equivalent .. ?
  • & 和 |和〜符号工作得很好,但等效不起作用源代码中没有符号..我想我必须调用等效函数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-19
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多