logical-operators - 简化逻辑表达式
问题描述
我正在寻找一种方法来简化这个逻辑表达式:
((x == y) and (x > 0 or z > 0))
or
((x != y) and (x > 0 and y > 0 and z > 0))
所有变量都是非负整数。
我考虑过使用Karnaugh Map,但我的变量不是布尔值,这会使事情复杂化。
然后我想我应该把它翻译成一组布尔变量,例如:
a = (x == y)
b = (x > 0)
c = (y > 0)
d = (z > 0)
但是这些布尔变量并不完全相互独立。
例如,如果a
是true
,则b
必须等于c
。
解决方案
我会以几种方式重写。但在继续之前,我必须说两件事。
如果有,你必须问你的队友要做出什么样的改进,因为他们是你代码的阅读者、审查者和维护者。他们可能想要简化,但有时他们只想在您的代码中添加更多注释。
您应该阅读堆栈溢出导览,它说“避免主要基于意见的问题,或者可能引发讨论而不是答案的问题。” 麻烦的是你的意见。有人有另一种看法。没关系。
重写
让我假设原始代码是这样的:
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")
您应该或不应该选择哪些选项?有替代品吗?再次,你必须问你的队友。
推荐阅读
- git - LFS 上传缺少对象但文件在那里
- python - Python中元组作为对象属性的不变性
- react-grid-layout - ReactGridLayout.children[0].y 必须是数字
- exception - 应该除以零引发异常
- asp.net-mvc - Asp Net Mvc Identity Multitenancy FindByEmailAsync 不工作
- spring - Spring 4 中的 ControllerAdvice 注释不起作用
- xamarin - Xamarin Forms - 如何让应用程序恢复到相同的视图 onResume
- arrays - BASH:在数组输出的一部分周围加双引号?
- c - 了解 UNIX fork() 如何影响父进程
- mongodb - 嵌套在数组中的数组的 MongoDB 投影