首页 > 解决方案 > 简化逻辑表达式

问题描述

我正在寻找一种方法来简化这个逻辑表达式:

((x == y) and (x > 0 or z > 0))
or
((x != y) and (x > 0 and y > 0 and z > 0))

所有变量都是非负整数。

我考虑过使用Karnaugh Map,但我的变量不是布尔值,这会使事情复杂化。

然后我想我应该把它翻译成一组布尔变量,例如:

但是这些布尔变量并不完全相互独立。

例如,如果atrue,则b必须等于c

标签: logical-operators

解决方案


我会以几种方式重写。但在继续之前,我必须说两件事。

  1. 如果有,你必须问你的队友要做出什么样的改进,因为他们是你代码的阅读者、审查者和维护者。他们可能想要简化,但有时他们只想在您的代码中添加更多注释。

  2. 您应该阅读堆栈溢出导览,它说“避免主要基于意见的问题,或者可能引发讨论而不是答案的问题。” 麻烦的是你的意见。有人有另一种看法。没关系。

重写

让我假设原始代码是这样的:

def executeNextStepIfPermitted(x, y, z):
  if ((x == y) and (x > 0 or z > 0)) or ((x != y) and (x > 0 and y > 0 and z > 0)):
    executeNextStep()
  raise Exception("Not permitted")

选项 1:删除不必要的()

def executeNextStepIfPermitted(x, y, z):
  if (x == y and (x > 0 or z > 0)) or (x != y and x > 0 and y > 0 and z > 0):
    executeNextStep()
  raise Exception("Not permitted")

选项 2:使用if ... elif而不是or

def executeNextStepIfPermitted(x, y, z):
  if x == y and (x > 0 or z > 0):
    executeNextStep()
  elif x != y and x > 0 and y > 0 and z > 0:
    executeNextStep()
  raise Exception("Not permitted")

选项 3:使用嵌套if而不是and

def executeNextStepIfPermitted(x, y, z):
  if x == y:
    if x > 0 or z > 0:
      executeNextStep()
  elif x != y:
    if x > 0 and y > 0 and z > 0:
      executeNextStep()
  raise Exception("Not permitted")

选项4:调用max()min()(有人说这并不简单。)

def executeNextStepIfPermitted(x, y, z):
  if x == y and max(x, z) > 0:
    executeNextStep()
  elif x != y and min(x, y, z) > 0:
    executeNextStep()
  raise Exception("Not permitted")

选项 5:在评论中解释

def executeNextStepIfPermitted(x, y, z):
  if x == y:
    if max(x, z) > 0:     # either of (x, z) is positive
      executeNextStep()
  elif x != y:
    if min(x, y, z) > 0:  # all of (x, y, z) are positive
      executeNextStep()
  raise Exception("Not permitted")

选项 6:以不言自明的方式使用和命名变量

def executeNextStepIfPermitted(x, y, z):
  eitherOfXzIsPositive = max(x, z) > 0
  allOfXyzArePositive = min(x, y, z) > 0

  if x == y and eitherOfXzIsPositive:
    executeNextStep()
  elif x != y and allOfXyzArePositive:
    executeNextStep()
  raise Exception("Not permitted")

您应该或不应该选择哪些选项?有替代品吗?再次,你必须问你的队友。


推荐阅读