Brian van den Broek wrote: >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)): > tvas.append(dict()) > > 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 > tvas[j][key]=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]), > print > >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 >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > What this shouts immediately to me, at least, is binary numbers and bool(). Just use your favorite binary conversion recipe, and count down from int(len(atoms)*"1",2), converting as you go. And then you take the boolean value of each digit of the binary number. If you need help, let me know as I've completed a working model.
HTH, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor