[Tutor] request for sugestions on fragement of code for generating truth-tables

Brian van den Broek broek at cc.umanitoba.ca
Sat Apr 1 02:32:16 CEST 2006

Hi all,

I've been too busy with life to do much Python of late. So, I am a bit
rusty. :-(

I've got some code that does what it needs to but I think I might be 
overlooking a much smoother way to get what I need.

The code takes a list of strings and returns a list of dictionaries, 
where each dictionary uses the strings from the list as keys and 
booleans as values. The dictionary list contains a dictionary 
exhibiting each possible combination of booleans over the keys, where 
these combinations are listed in a systematic way.

This code works:

def tva_dict_maker(atoms):

     tvas = []
     val = False

     for k in range(2**len(atoms)):

     for i in range(len(atoms)):
         key = atoms[i]

         for j in range(2**len(atoms)):
             if j % ( len(tvas) / 2.0 ** (i+1) ) == 0:
                 val = not val

     return tvas

The output I desire is easier to see with a bit of processing (to 
impose order on the dicts). So,

def display_tvas(tvas):
     for i in tvas:
	for j in sorted(i):
		print "%s:%s\t" %(j, i[j]),

Then, the output is like so:

 >>> atoms = ["a","b","c"]
 >>> tvas = tva_dict_maker(atoms)
 >>> display_tvas(tvas)
a:True	b:True	c:True	
a:True	b:True	c:False	
a:True	b:False	c:True	
a:True	b:False	c:False	
a:False	b:True	c:True	
a:False	b:True	c:False	
a:False	b:False	c:True	
a:False	b:False	c:False	

As desired :-)

But, I can't shake the feeling I'm doing this in a harder than 
necessary way :-|

[This is in the context of writing a program to generate truth-tables 
for sentential logic, so that I can easily create answered exercises 
for a critical thinking course I've been teaching. (As it is for a 
Philosophy class, the truth-values are listed in the opposite order 
than in a CompSci context.)]

Any suggestions would be welcome.

Best to all,

Brian vdB

More information about the Tutor mailing list