用于生成n个变量的所有可能布尔函数的算法

时间:2014-03-24 03:24:03

标签: algorithm boolean-logic

对于n个变量,存在2 ^(2 ^ n)个不同的布尔函数。例如,如果n = 2,则存在16种可能的布尔函数,这些函数可以以产品形式或和形式的乘积的总和来编写。可能的函数数量随着n。指数呈指数增长。

我正在寻找一种能够为n个变量生成所有这些可能的布尔规则的算法。我试图在各个地方搜索,但到目前为止还没有找到合适的地方。大多数算法都与将布尔函数简化或简化为标准形式有关。

我知道即使对于n = 8或9,规则的数量也会变得太大,但如果存在相关算法,有人可以帮助我吗?

3 个答案:

答案 0 :(得分:8)

n 变量的布尔函数具有 2 ^ n 可能的输入。这些可以通过打印0 <= x < 2^n范围内的值的二进制表示来枚举。

对于每个可能的输入,布尔函数可以输出 0 1 。列举所有可能性(即每个可能的真值表)。列出范围0 <= x < 2^(2^n)中的二进制值。

这是Python中的算法:

from __future__ import print_function
from itertools import product       # forms cartesian products
n = 3                               # number of variables

print('All possible truth tables for n =', n)
inputs = list(product([0, 1], repeat=n))
for output in product([0, 1], repeat=len(inputs)):
    print()
    print('Truth table')
    print('-----------')
    for row, result in zip(inputs, output):
        print(row, '-->', result)

输出如下:

All possible truth tables for n = 3

Truth table
-----------
(0, 0, 0) --> 0
(0, 0, 1) --> 0
(0, 1, 0) --> 0
(0, 1, 1) --> 0
(1, 0, 0) --> 0
(1, 0, 1) --> 0
(1, 1, 0) --> 0
(1, 1, 1) --> 0

Truth table
-----------
(0, 0, 0) --> 0
(0, 0, 1) --> 0
(0, 1, 0) --> 0
(0, 1, 1) --> 0
(1, 0, 0) --> 0
(1, 0, 1) --> 0
(1, 1, 0) --> 0
(1, 1, 1) --> 1

Truth table
-----------
(0, 0, 0) --> 0
(0, 0, 1) --> 0
(0, 1, 0) --> 0
(0, 1, 1) --> 0
(1, 0, 0) --> 0
(1, 0, 1) --> 0
(1, 1, 0) --> 1
(1, 1, 1) --> 0

Truth table
-----------
(0, 0, 0) --> 0
(0, 0, 1) --> 0
(0, 1, 0) --> 0
(0, 1, 1) --> 0
(1, 0, 0) --> 0
(1, 0, 1) --> 0
(1, 1, 0) --> 1
(1, 1, 1) --> 1

... and so on 

如果你想要以代数形式而不是真值表输出,那么算法是相同的:

from __future__ import print_function
from itertools import product       # forms cartesian products
n = 3                               # number of variables

variables = 'abcdefghijklmnopqrstuvwxyz'[:n]
pairs = [('~'+var, var) for var in variables]
print('All possible algebraic expressions for n =', n)

inputs = list(product(*pairs))
for i, outputs in enumerate(product([0, 1], repeat=len(inputs))):
    terms = [''.join(row) for row, output in zip(inputs, outputs) if output]
    if not terms:
        terms = ['False']
    print('Function %d:' % i, ' or '.join(terms))

输出如下:

All possible algebraic expressions for n = 3
Function 0: False
Function 1: abc
Function 2: ab~c
Function 3: ab~c or abc
Function 4: a~bc
Function 5: a~bc or abc
Function 6: a~bc or ab~c
Function 7: a~bc or ab~c or abc
Function 8: a~b~c
Function 9: a~b~c or abc
Function 10: a~b~c or ab~c
Function 11: a~b~c or ab~c or abc
Function 12: a~b~c or a~bc
Function 13: a~b~c or a~bc or abc
Function 14: a~b~c or a~bc or ab~c
Function 15: a~b~c or a~bc or ab~c or abc
Function 16: ~abc
Function 17: ~abc or abc
Function 18: ~abc or ab~c
Function 19: ~abc or ab~c or abc
Function 20: ~abc or a~bc
Function 21: ~abc or a~bc or abc
Function 22: ~abc or a~bc or ab~c
Function 23: ~abc or a~bc or ab~c or abc
Function 24: ~abc or a~b~c
Function 25: ~abc or a~b~c or abc
Function 26: ~abc or a~b~c or ab~c
Function 27: ~abc or a~b~c or ab~c or abc
Function 28: ~abc or a~b~c or a~bc
Function 29: ~abc or a~b~c or a~bc or abc
Function 30: ~abc or a~b~c or a~bc or ab~c
Function 31: ~abc or a~b~c or a~bc or ab~c or abc
Function 32: ~ab~c
Function 33: ~ab~c or abc

... and so on 

答案 1 :(得分:3)

正如评论中所提到的,数字与真值表之间存在一对一的关系。例如,我们可以代表真值表

0 0 0  | 1
0 0 1  | 1
0 1 0  | 0
0 1 1  | 0
1 0 0  | 1
1 0 1  | 0 
1 1 0  | 1
1 1 1  | 0

由二进制数01010011(最上面的行由最低有效位表示)。

显然只是循环数字来生成这些表示:

for f := 0 to 2^(2^n) - 1:
    # do something with f

我们可以对f做些什么?例如,我们可以对其进行评估。假设我们想知道f(0,1,0)。它就像将二进制数x = 010解释为一样简单并做一些魔术一样简单:

def evaluate(f, x):
    return (f & (1<<x)) != 0

我们也可以通过检查哪些位是0来找到它的析取范式:

def dnf(f):
    for x := 0 to 2^n - 1:
        if f & (1<<x) != 0:
            print binary(x) + " OR "

为上述功能提供000 OR 001 OR 100 OR 110 (OR)之类的结果。

答案 2 :(得分:2)

我已经更改了Raymond Hettinger发布的代码。 现在你可以:

  1. 生成所有布尔表达式,最多为n_ary,
  2. 选择一个特定的功能,
  3. 执行评估,
  4. 以二进制或真/假的方式获得答案。
  5. 代码:

        from itertools import product
    
        def allBooleanFunctions(kk):
            """Finds all Boolean functions for indegree kk"""
            inputs1 = list(product([0, 1], repeat=kk))
            variables = 'abcdefghijklmnopqrstuvwxyz'[:kk]
            pairs = [('( not '+var+' )', var) for var in variables]
            inputs = list(product(*pairs))
    
            bool_func=[]
    
            for i, outputs in enumerate(product([0, 1], repeat=len(inputs))):
                terms = [' and '.join(row) for row, output in zip(inputs, outputs) if output]
                if not terms:
                    terms = ['False'] 
                bool_func.append(('('+(') or ('.join(terms))+')'))
            return bool_func
    
        n_ary=2 # number of inputs; keep it n_ary<=5
    
        boolean_function_analytical=allBooleanFunctions(n_ary)
    
        print('All Boolean functions of indegree:'+str(n_ary)+'\n')
        print(boolean_function_analytical)
        print
        print('A Boolean function:'+'\n')
        print(boolean_function_analytical[2])
        # Evaluate third boolean function:
        a=1 # first input
        b=0 # second input
        c=0 # third input
        d=0 # fourth input
        print('a='+str(a)+'; b='+str(b)+'; c='+str(c)+'; d='+str(d)+'\n')
        print('Evaluation in 0/1 manner:')
        print(int(eval((boolean_function_analytical[2]))))
        print('Evaluation in True/False manner:')
        print(bool(eval((boolean_function_analytical[2]))))
    

    结果:

        All Boolean functions of indegree:2
    
        ['(False)', '(a and b)', '(a and ( not b ))', '(a and ( not b )) or (a and b)', '(( not a ) and b)', '(( not a ) and b) or (a and b)', '(( not a ) and b) or (a and ( not b ))', '(( not a ) and b) or (a and ( not b )) or (a and b)', '(( not a ) and ( not b ))', '(( not a ) and ( not b )) or (a and b)', '(( not a ) and ( not b )) or (a and ( not b ))', '(( not a ) and ( not b )) or (a and ( not b )) or (a and b)', '(( not a ) and ( not b )) or (( not a ) and b)', '(( not a ) and ( not b )) or (( not a ) and b) or (a and b)', '(( not a ) and ( not b )) or (( not a ) and b) or (a and ( not b ))', '(( not a ) and ( not b )) or (( not a ) and b) or (a and ( not b )) or (a and b)']
    
        A Boolean function:
    
        (a and ( not b ))
        a=1; b=0; c=0; d=0
    
        Evaluation in 0/1 manner:
        1
        Evaluation in True/False manner:
        True
    

    玩得开心!!!