Python Forum
Check multiple cases - Python 3.7
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Check multiple cases - Python 3.7
#1
Hi guys.

This is the framework's API: http://www.logicthrupython.org/api/

def evaluate(formula: Formula, model: Model) -> bool:
    """Calculates the truth value of the given formula in the given model.

    Parameters:
        formula: formula to calculate the truth value of.
        model: model over (possibly a superset of) the variables of the formula,
            to calculate the truth value in.

    Returns:
        The truth value of the given formula in the given model.

    Examples:
        >>> evaluate(Formula.parse('~(p&q76)'), {'p': True, 'q76': False})
        True

        >>> evaluate(Formula.parse('~(p&q76)'), {'p': True, 'q76': True})
        False
    """
    assert is_model(model)
    assert formula.variables().issubset(variables(model))
    if is_constant(formula.root):
        return True if formula.root == "T" else False
    if is_variable(formula.root):
        return model[formula.root]
    if is_unary(formula.root):
        return not evaluate(formula.first, model)

    binary_op: str = formula.root  # & | ->
    if binary_op == "&":
        return evaluate(formula.first, model) and evaluate(
            formula.second, model
        )
    if binary_op == "|":
        return evaluate(formula.first, model) or evaluate(formula.second, model)
    # ->
    return not evaluate(formula.first, model) or evaluate(formula.second, model)
This is a test for code functionality if someone is interested: https://pastebin.com/cVB4SYNg

I'd be glad if someone can review my code and take some advices.
I'm not sure the way I handle the unary case is super-elegant, as well as the way I'm checking each of the binary operators.


Thanks in advance.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020