Building truth tables

Aaron "Castironpi" Brady castironpi at gmail.com
Fri Sep 26 14:01:44 EDT 2008


On Sep 26, 11:40 am, "Tim Rowe" <digi... at gmail.com> wrote:
> 2008/9/26 andrea <kerny... at gmail.com>:
>
> > Well I would like to make a little program that given a certain
> > logical expression gives the complete truth table.
>
> > It's not too difficult in fact, I just have some doubts on how to
> > design it.
>
> > I thought something like that:
>
> > class Term:
>
> > class Table:
>
> >   def and(...
> >   def or(...
>
> As a quick and dirty solution, I'd write a function that takes a
> function as a parameter.
>
> Starting with a helper function to separate the bits of an integer
> into a list of bools:
>
> def int_to_bool(i, bits):
>         # Extract the bits of i to a boolean array.
>         # 'bits' is the number of signifcant bits.
>         result = []
>         for j in range(0, bits):
>                 result.append(i & 1)
>                 i >>= 1
>         result.reverse()
>         return result
>
> Now I'd define a function such as:
> def table(f, n):
>         # Calculate a truth table for function f taking n boolean parameters
>         result = []
>         for i in range(0, math.pow(2, n)):
>                 for j in range(0, n):
>                         params = int_to_bool(i, n)
>                 result.append(params + [(f(*params))])
>         return result
>
> Now you could define the function you want as a separate function, or
> just use a lambda:
>
> table(lambda a, b, c:(a or b) and c, 3)
> [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 1, 1, 1], [1, 0, 0, 0],
> [1, 0, 1, 1], [1, 1, 0, 0], [1, 1, 1, 1]]
>
> Each element in the result is the state of the parameters followed by
> the result of the function.
>
> I stress that this is quick and dirty -- I'm sure somebody will be
> along with something better soon!
>
> --
> Tim Rowe

Good idea.  If you want prefixed operators: 'and( a, b )' instead of
'a and b', you'll have to write your own.  ('operator.and_' is bitwise
only.)  It may be confusing to mix prefix with infix: 'impl( a and b,
c )', so you may want to keep everything prefix, but you can still use
table( f, n ) like Tim said.



More information about the Python-list mailing list