[Edu-sig] boolean expression

Marc Keller mkeller@noos.fr
Sun, 14 Oct 2001 15:31:24 +0200


A variation on your Boolean module, leaving Python evaluates boolean
expressions, with local names as arguments:

def bin(num,nbits=0):
    b, q = '', num
    while q !=0  or nbits > len(b):
        b, q = `q&1 > 0` + b, q>>1
    return b

def domainBool(n):
     return [tuple(map(int,tuple(bin(x,n)))) for x in range(2**n)]

def truth(expr,*args):
     n = len(args)
     print n*'%s '%args+'|',expr
     print n*'=='+'|='+len(expr)*'='
     locals = {}
     for v in domainBool(n):
          for i in range(n):
               locals[args[i]] = v[i]
      print n*'%d '%v+'|',center(str(eval(expr,locals)),len(expr))


Examples
>>> truth('not a','a')
a | not a
==|======
0 |   1
1 |   0
>>> expr = "(a and not b) or c"
>>> truth(expr,'a', 'b', 'c')
a b c | (a and not b) or c
======|===================
0 0 0 |         0
0 0 1 |         1
0 1 0 |         0
0 1 1 |         1
1 0 0 |         1
1 0 1 |         1
1 1 0 |         0
1 1 1 |         1