473,396 Members | 1,755 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Building truth tables

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(...
But I'm not convinced...
I would like something like that more or less:
a,b,c = Term()

table([a,b,c], impl(and(or(a,b)),c))

Any idea??
Thanks
Sep 26 '08 #1
5 6574
2008/9/26 andrea <ke******@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
Sep 26 '08 #2
On Sep 26, 11:40*am, "Tim Rowe" <digi...@gmail.comwrote:
2008/9/26 andrea <kerny...@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 booleanparameters
* * * * 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.
Sep 26 '08 #3
On 26 Set, 20:01, "Aaron \"Castironpi\" Brady" <castiro...@gmail.com>
wrote:
>
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.
After a while I'm back, thanks a lot, the truth table creator works,
now I just want to parse some strings to make it easier to use.

Like

(P \/ Q) -S == S

Must return a truth table 2^3 lines...

I'm using pyparsing and this should be really simple, but it doesn't
allow me to recurse and that makes mu stuck.
The grammar BNF is:

Var :: = [A..Z]
Exp ::= Var | !Exp | Exp \/ Exp | Exp -Exp | Exp /\ Exp | Exp ==
Exp

I tried different ways but I don't find a smart way to get from the
recursive bnf grammar to the implementation in pyparsing...
Any hint?
Oct 24 '08 #4
On Oct 24, 5:53*am, andrea <kerny...@gmail.comwrote:
On 26 Set, 20:01, "Aaron \"Castironpi\" Brady" <castiro...@gmail.com>
wrote:
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.

After a while I'm back, thanks a lot, the truth table creator works,
now I just want to parse some strings to make it easier to use.

Like

(P \/ Q) -S == S

Must return a truth table 2^3 lines...

I'm using pyparsing and this should be really simple, but it doesn't
allow me to recurse and that makes mu stuck.
The grammar BNF is:

Var :: = [A..Z]
Exp ::= Var | !Exp *| Exp \/ Exp | Exp -Exp | Exp /\ Exp | Exp ==
Exp

I tried different ways but I don't find a smart way to get from the
recursive bnf grammar to the implementation in pyparsing...
Any hint?
Use Forward to create a recursive grammar. Look at the examples page
on the pyparsing wiki, and there should be several samples of
recursive grammars.

Here is a very simple recursive grammar, with no precedence to your
operators:

from pyparsing import oneOf, alphas, Forward, ZeroOrMore, Group,
Optional
var = oneOf(list(alphas))
op = oneOf(r"\/ /\ -==")
expr = Forward()
expr << Optional('!') + ( var | Group('(' + expr + ')') ) +
ZeroOrMore(op + expr)

test = "(P \/ Q) -S == S"

print expr.parseString(test).asList()

prints:

[['(', 'P', '\\/', 'Q', ')'], '->', 'S', '==', 'S']
Since these kinds of expressions are common, pyparsing includes a
helper method for defining precedence of operations infix notation:

from pyparsing import operatorPrecedence, opAssoc

expr = operatorPrecedence(var,
[
(r'!', 1, opAssoc.RIGHT),
(r'\/', 2, opAssoc.LEFT),
(r'/\\', 2, opAssoc.LEFT),
(r'->', 2, opAssoc.LEFT),
(r'==', 2, opAssoc.LEFT),
])

print expr.parseString(test).asList()

prints:

[[[['P', '\\/', 'Q'], '->', 'S'], '==', 'S']]

HTH,
-- Paul
Oct 25 '08 #5
On Oct 24, 5:53*am, andrea <kerny...@gmail.comwrote:
On 26 Set, 20:01, "Aaron \"Castironpi\" Brady" <castiro...@gmail.com>
wrote:
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.

After a while I'm back, thanks a lot, the truth table creator works,
now I just want to parse some strings to make it easier to use.

Like

(P \/ Q) -S == S

Must return a truth table 2^3 lines...

I'm using pyparsing and this should be really simple, but it doesn't
allow me to recurse and that makes mu stuck.
The grammar BNF is:

Var :: = [A..Z]
Exp ::= Var | !Exp *| Exp \/ Exp | Exp -Exp | Exp /\ Exp | Exp ==
Exp

I tried different ways but I don't find a smart way to get from the
recursive bnf grammar to the implementation in pyparsing...
Any hint?
Tell you what. At the risk of "carrot-and-stick, jump-how-high"
tyranny, I'll show you some output of a walk-through. It should give
you an idea of the process. You can always ask for more hints.

( ( ( !( R ) /\ ( !( P \/ Q ) ) ) -S ) == S )
(((!(R)/\(!(P\/Q)))->S)==S)
(((!R/\(!(P\/Q)))->S)==S)
n1 := !R
(((n1/\(!(P\/Q)))->S)==S)
n2 := P\/Q
(((n1/\(!(n2)))->S)==S)
(((n1/\(!n2))->S)==S)
n3 := !n2
(((n1/\(n3))->S)==S)
(((n1/\n3)->S)==S)
n4 := n1/\n3
(((n4)->S)==S)
((n4->S)==S)
n5 := n4->S
((n5)==S)
(n5==S)
n6 := n5==S
(n6)
n6
{'n1': (<function not_ at 0x00A04070>, '!R', ('R',)),
'n2': (<function or_ at 0x00A040F0>, 'P\\/Q', ('P', 'Q')),
'n3': (<function not_ at 0x00A04070>, '!n2', ('n2',)),
'n4': (<function and_ at 0x00A040B0>, 'n1/\\n3', ('n1', 'n3')),
'n5': (<function imp_ at 0x00A04130>, 'n4->S', ('n4', 'S')),
'n6': (<function eq_ at 0x00A04170>, 'n5==S', ('n5', 'S'))}
{'Q': True, 'P': True, 'S': True, 'R': True} True
{'Q': True, 'P': True, 'S': False, 'R': True} False
{'Q': True, 'P': True, 'S': True, 'R': False} True
{'Q': True, 'P': True, 'S': False, 'R': False} False
{'Q': False, 'P': True, 'S': True, 'R': True} True
{'Q': False, 'P': True, 'S': False, 'R': True} False
{'Q': False, 'P': True, 'S': True, 'R': False} True
{'Q': False, 'P': True, 'S': False, 'R': False} False
{'Q': True, 'P': False, 'S': True, 'R': True} True
{'Q': True, 'P': False, 'S': False, 'R': True} False
{'Q': True, 'P': False, 'S': True, 'R': False} True
{'Q': True, 'P': False, 'S': False, 'R': False} False
{'Q': False, 'P': False, 'S': True, 'R': True} True
{'Q': False, 'P': False, 'S': False, 'R': True} False
{'Q': False, 'P': False, 'S': True, 'R': False} True
{'Q': False, 'P': False, 'S': False, 'R': False} True

Before you trust me too much, you might want to check at least some of
these, to see if the starting (complicated) expression is evaluated
correctly. I didn't.
Oct 25 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Good Man | last post by:
Hi there I'm in the planning stages of creating a database, and I have two options here. Which makes more sense, and/or provides better performance for queries - a single table with hundreds of...
1
by: rsd | last post by:
how do you specify the "colspan" attribut of a <td> cell when building the table/rows/cells dynamicly? ie: lets say we have the follwoing code: table = document.all; // header row tr1 =...
0
by: Mac MCCall | last post by:
I am doing work for a community that currently has four different MS-Access databases which are at four separate locations but have a great deal of overlapping data. There is a residents...
0
by: matt | last post by:
(first -- does anyone know of a good CR group?) hello, i am new to CR. i have created one report that queries the db and presents the data to the user in a tabular-like format. however, i...
1
by: Franck | last post by:
Hi, I'd like to know if it's possible to get server side relationship when building Link Tables in my AccessFront End. Basic Sample : In my Sql Server 2005 DataBase, I've got Table2 which is...
2
by: wujtehacjusz | last post by:
Dear All I am very new to MS SQL Server and I am wondering is there some tool which would allow me to build pivot tables in SQL more easily. At the moment writing a query can be quite...
6
by: ambanks04 | last post by:
ok taking computer science class anybody know what to do i am not computer literate CoSc 111.003 Spring 2008 Assignment 4 1) Each student shall design, develop, code, test and submit an...
7
by: papacologne | last post by:
Given the truth values of the propositions p and q, display the truth values of the conjunction, disjunction, exclusive or, conditional statement, and biconditional of these propositions. Can you...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.