Difference between revisions of "CSC270 GenerateTruthTable.py"
Line 12: | Line 12: | ||
# _ _ _ | # _ _ _ | ||
# g = a + b + c | # g = a + b + c | ||
+ | |||
def f( a, b, c ): | def f( a, b, c ): | ||
− | return ( a | + | return ( a & (not b) ) | c |
def g( a, b, c ): | def g( a, b, c ): | ||
− | |||
+ | return (not a) | (not b) | (not c) | ||
def main(): | def main(): | ||
Line 26: | Line 27: | ||
for c in [ 0, 1 ]: | for c in [ 0, 1 ]: | ||
print "%3d%3d%3d |%3d%3d" % \ | print "%3d%3d%3d |%3d%3d" % \ | ||
− | ( a, b, c, f( a, b, c ), g( a, b, c ) ) | + | ( a, b, c, f( a, b, c ), g( a, b, c ) ) |
− | |||
main() | main() | ||
+ | |||
+ | |||
</pre></code> | </pre></code> |
Revision as of 12:06, 4 February 2009
One can use python (or any other language) to easily generate truth tables. This is a simple way to test a hypothesis, or to verify special cases in design situations. Don't hesitate to use this approach to save time and generate accurate results.
# truthtable.py
# D. Thiebaut
# how a simple python program can generate the
# truth table of a boolean function
#
# here f is a function of 3 variables
# _
# f = a.b + c
# _ _ _
# g = a + b + c
def f( a, b, c ):
return ( a & (not b) ) | c
def g( a, b, c ):
return (not a) | (not b) | (not c)
def main():
print " a b c | f g "
print "-----------+--------"
for a in [ 0, 1 ]:
for b in [ 0, 1 ]:
for c in [ 0, 1 ]:
print "%3d%3d%3d |%3d%3d" % \
( a, b, c, f( a, b, c ), g( a, b, c ) )
main()
The output is show below:
a b c | f g
-----------+--------
0 0 0 | 0 1
0 0 1 | 1 1
0 1 0 | 0 1
0 1 1 | 1 1
1 0 0 | 1 1
1 0 1 | 1 1
1 1 0 | 0 1
1 1 1 | 1 0