Building truth tables

Tim Rowe digitig at gmail.com
Fri Sep 26 12:40:18 EDT 2008


2008/9/26 andrea <kerny404 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



More information about the Python-list mailing list