【问题标题】:OOP in Python , Getting Truth Table using Tree modelPython中的OOP,使用树模型获取真值表
【发布时间】:2022-01-03 01:51:33
【问题描述】:

所以我被赋予了使用 OOP 来获得以下真值表的任务。我必须在表达式上制作方法 make_tt(),即

e=Eq(NOT(Var('y')),Var('x')) 

这样它会返回以下真值表。

其中,Eq 代表 '==' 而不是代表 '!'

   y | x    | !y==x
True | True | False
False| True | True
True | False| True
False| False| False

我首先创建了父类 Expr,我将从中创建 Eq 和 Not 类以继承常见的东西,但我不知道如何编写 make_tt() 以使其产生以下结果。

class Expr:
  def __init__ (self,left,right):
    self.left=left
    self.right=right

  def __str__(self):
    return f'{self.left}{self.sign}{self.right}'

class Not(Expr):
  def __init__(self,variable):
    self.variable=variable

  sign='!'

  def __str__(self):
    return f'{self.sign}{self.variable}'

class Eq(Expr):
  sign='=='

class Var:
  def __init__(self,value):
    self.value=value

  def __str__(self):
    return str(self.value)

e=Eq(NOT(Var('y')),Var('x'))

如果我这样做

e.make_tt()

它应该产生如你在上面看到的真值表。

   y | x    | !y==x
True | True | False
False| True | True
True | False| True
False| False| False

【问题讨论】:

    标签: python-3.x oop recursion tree


    【解决方案1】:

    真值表需要涵盖输入值的所有组合。使用二进制值,每个变量都有两种状态:真/假。这意味着对于表中的每个变量,您的组合数将乘以 2。

    例如:

    vars a,b,c   -> 2*2*2   =  8 total combinations
    vars a,b,c,d -> 2*2*2*2 = 16 total combinations
    

    这就是为什么在给定变量 y/x 的情况下,您需要一个包含 4 行 + 标题的表格。 (y,x -> 2*2 = 4 total) 最后一列是您将某个值的变量插入等式时得到的结果,在这种情况下是(不是 y == x)。

    您需要做的是首先使用可能的组合填充列表或字典或其他一些数据容器。然后,您遍历该组合序列并将每个组合传递到您的方程中,该方程应返回其真值。如果您将表达式的返回值与您使用的组合一起记录下来,您基本上已经创建了真值表,然后只需将其打印到控制台即可。

    包含组合的一个示例是使用元组列表,如下所示:

    combinations = [(1,1), (0,1), (1,0), (0,0)] (1 表示真,0 表示假)

    然后您可以通过将一个元组分配给两个变量来获取变量,如下所示:

    y,x = combinations[1] 导致y=0, x=1,因为它获得了列表中的第二个组合。如果你把它代入方程,你会得到:not y == x --> not 0 == 1 --> 1 == 1 --> True 所以(False,True)的组合结果是True

    这应该让你开始。我建议在 python 中玩耍并测试不同的方法来使用它来构建你的表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-17
      • 2015-06-05
      • 1970-01-01
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多