python - 如何为所有 2^N bool 条件编写 If 语句(python)

标签 python algorithm

我有一个函数需要根据输入的查询实例执行查询.. 但是随着条件的增加,我要列出所有这些变得很乏味。 例如: 假设我最初有两个条件:

if (cond_1 == True and cond_2 == False):
    do something
elif  cond_1 == True and cond_2 == True:
    do something else
elif cond_1 == False and cond_2 == True:
    do this

....

所以我想如果条件采用二进制值,那么我必须写 2^n 条语句 :(

所以现在我有 3 个条件变量(8 个语句).. 我担心这个数字将来可能会增加。 是否有更好的方法来检查这些条件??

最佳答案

您是否需要始终写出所有 2^n 种可能性?

您必须做的所有事情都不同吗(还有 2^n 个操作?)

不过我可以给一些提示:

不要使用“== True”或“== False”

你写的等于:

if cond_1 and not cond_2:
    do something 
elif cond_1 and cond_2:
    do something else 
elif not cond_1 and cond_2:
    do this 

同时考虑写作:

if cond_1:
    if cond_2:
        Do something
    else:
        Do something 
else:
    if cond_2:
        Do something
    else:
        Do something 

您还可以根据值定义函数:

def __init__(self):
    self.actions = {
      (False, False): action_1,
      (False, True ): action_2,
      ...
    }

def action_1(self):
    some action

def action_2(self):
    some action

....

并调用它:

self.actions[(cond_1, cond_2)]()

如果你想优化选项的数量,以防你有不同的条件和类似的 Action ,看看卡诺 map (它比看起来更容易):

http://en.wikipedia.org/wiki/Karnaugh_map

关于python - 如何为所有 2^N bool 条件编写 If 语句(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9525575/

相关文章:

algorithm - 有向无环图的差异

python - Python 3 中的类 "keyword arguments"

python - 所需输出

python - 有没有一种方法可以有效地生成包含数百万个文件的目录中的每个文件?

python - 如何打印 python 数组中的列?

algorithm - 将 block 对角矩阵乘以向量的有效方法

python - 使用wsgi在apache上部署flask app时如何解决权限错误?

c - 坂本智彦的算法是如何工作的?需要详细解释

c# - 创建一个 "spell check"以合理的运行时间检查数据库

algorithm - 如果已知边数,创建最小生成树的时间复杂度