write a function that computes the truth table of a statement in propositional l
ID: 3872692 • Letter: W
Question
write a function that computes the truth table of a statement in propositional logic along with several functions that reason about those tables.
Let’s start with the task of computing the truth table of a proposition, and describe it informally first. We want to be able to do something like:
where expression is a string that contains a valid Python logical expression, and the return value is a list where each element is a row in the table, e.g.:
the row [True, False, False] in the truth table corresponds to a=True, b=False and a result of False. The expressions can be more complicated than ‘a and b’, e.g. ‘(a and b) or (c and not d)’.
You already know that in Python you can easily evaluate logical expressions, i.e. propositions:
But, at this point you may ask how you can evaluate arbitrary expressions without even knowing the names of the variables ahead of time. Turns out it’s quite simple in Python using the exec and evalbuiltins:
We are providing you with template code that contains some black magic that enriches Python’s Boolean operators (and, or, not) with two additional operators: |iff| and |implies| that correspond to the bi-conditional (<—>) and implication (—>) operators, respectively. Using the template code you’ll be able to evaluate expressions such as:
the code:
Explanation / Answer
main.py
from functools import partial
import re
class Infix(object):
def __init__(self, func):
self.func = func
def __or__(self, other):
return self.func(other)
def __ror__(self, other):
return Infix(partial(self.func, other))
def __call__(self, v1, v2):
return self.func(v1, v2)
@Infix
def implies(p, q) :
return not p or q
@Infix
def iff(p, q) :
return (p |implies| q) and (q |implies| p)
# You must use this function to extract variables
# This function takes an expression as input and returns a sorted list of variables
# Do NOT modify this function
def extract_variables(expression):
sorted_variable_set = sorted(set(re.findall(r'[a-z]', expression)))
return sorted_variable_set
# *********************** END ***************************
############## IMPLEMENT THE FOLLOWING FUNCTIONS ##############
############## Do not modify function definitions ##############
def truth_table(expression):
variables = extract_variables(expression)
table = []
for number in range(0, 2**len(variables)):
bits = []
numCopy = number
for i in range(len(variables) - 1, -1, -1):
if (numCopy / (2**i) >= 1):
bits.append(1)
numCopy -= (2**i)
else:
bits.append(0)
for i in range(0, len(bits)):
exec(variables[i] + "=" + ('True' if bits[i] else 'False'))
answer = []
for i in range(0, len(bits)):
answer.append(True if bits[i] else False)
answer.append(eval(expression))
table.append(answer)
return table
pass
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.