[docs]classTruthTable:"""Generates a truth table for a given logical expression."""def__init__(self,expression:LogicalExpression):ifnotisinstance(expression,LogicalExpression):raiseTypeError("TruthTable requires a LogicalExpression instance.")self.expression=expression
[docs]defgenerate(self)->List[Dict[str,Union[bool,str]]]:""" Generates all possible truth values for the logical expression. Returns: List of dictionaries, where each dictionary represents a row in the truth table. """variables=sorted(self.expression.variables())# Ensure sorted order of variablestable=[]forvaluesinproduct([False,True],repeat=len(variables)):context=dict(zip(variables,values,strict=False))# Maintain consistent ordertry:result=self.expression.evaluate(context)exceptExceptionase:result=f"Error: {e}"# Store error message for debuggingrow={var:context[var]forvarinvariables}# Preserve variable orderrow["Result"]=resulttable.append(row)returntable
[docs]defis_tautology(self)->bool:""" Checks if the expression is always true. Returns: True if the expression evaluates to True for all assignments, otherwise False. """returnall(row["Result"]isTrueforrowinself.generate())
[docs]defis_contradiction(self)->bool:""" Checks if the expression is always false. Returns: True if the expression evaluates to False for all assignments, otherwise False. """returnall(row["Result"]isFalseforrowinself.generate())
[docs]defis_satisfiable(self)->bool:""" Checks if there exists a truth assignment that makes the expression true. Returns: True if at least one assignment makes the expression True, otherwise False. """returnany(row["Result"]isTrueforrowinself.generate())