🛠️ToolsShed

Generador de Tabla de Verdad

Ingresa una expresión booleana con AND, OR, NOT, XOR y obtén una tabla de verdad completa.

Operators: AND, OR, NOT, XOR, NAND, NOR, XNOR (or &, |, !, ^)

Preguntas Frecuentes

Implementación de Código

from itertools import product

def truth_table(variables, expression):
    """Generate a truth table for a logical expression."""
    headers = variables + [expression]
    print(" | ".join(f"{h:>6}" for h in headers))
    print("-" * (9 * len(headers)))

    for values in product([False, True], repeat=len(variables)):
        env = dict(zip(variables, values))
        # Replace logical notation with Python
        expr = expression
        expr = expr.replace("AND", "and").replace("OR", "or").replace("NOT", "not")
        expr = expr.replace("∧", " and ").replace("∨", " or ").replace("¬", " not ")
        result = eval(expr, {}, env)

        row = [str(v) for v in values] + [str(result)]
        print(" | ".join(f"{v:>6}" for v in row))

# Example: P AND Q
truth_table(["P", "Q"], "P and Q")
print()

# Example: P OR (NOT Q)
truth_table(["P", "Q"], "P or (not Q)")
print()

# Check tautology: P OR NOT P
truth_table(["P"], "P or (not P)")

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.