## Saturday, November 22, 2008

### 99 problems - python - 48

Truth tables for logical expressions (3).

Generalize problem P47 in such a way that the logical expression may contain any number of logical variables. Define table/2 in a way that table(List,Expr) prints the truth table for the expression Expr, which contains the logical variables enumerated in List.
`Example:* (table (A,B,C) (A and (B or C) equ A and B or A and C))true true true truetrue true fail truetrue fail true truetrue fail fail truefail true true truefail true fail truefail fail true truefail fail fail truedef int_to_bool_tuple(x,size):    result = []    while x:        result.insert(0, (x & 1) == 1)        x >>= 1    return ([False]*(size-len(result))) + result    def table2(var_count, func):    for x in range(2**var_count):        bools = int_to_bool_tuple(x,var_count)        for b in bools:            print "%-5s" % b,        print func(*bools)`

As I was exploring ideas for this solution I noticed that python 2.6 has a bin() function which gives a string representation of a number as binary. Need to upgrade to 2.6 I guess. Of course if I'm going to upgrade, might as well wait for 3.0.