Projekt_Logika_1/logic_formula_checker/utils.py

45 lines
1.5 KiB
Python
Raw Normal View History

2018-06-07 10:44:41 +02:00
from .types import SupportSign, SentenceConjunction, SentenceVariable, Negation
def is_formula_correct(formula):
""" Run all test on formula """
if not formula:
return True
else:
formula = formula.replace(' ', '')
return all([check_order(formula), check_parenthesis(formula)])
def check_parenthesis(formula: str) -> bool:
""" Check if all brackets are opened and closed correctly """
stack_of_expected_sings = []
for sign in formula:
if sign in SupportSign.symbols_open:
inverse_of_sign = SupportSign.get_closed_symbol(sign)
stack_of_expected_sings.append(inverse_of_sign)
elif sign in SupportSign.symbols_close:
if stack_of_expected_sings.pop() != sign:
return False
return not stack_of_expected_sings
def check_order(formula: str) -> bool:
""" Check if all sings have correct preceding and next sign """
expected_sign = []
for sign in formula:
if sign in SupportSign.symbols:
continue
if expected_sign and sign not in expected_sign:
return False
if sign in Negation.symbols:
expected_sign = SentenceVariable.symbols
elif sign in SentenceConjunction.symbols:
expected_sign = Negation.symbols + SentenceVariable.symbols
elif sign in SentenceVariable.symbols:
expected_sign = SentenceConjunction.symbols
return any(symbol in expected_sign for symbol in SentenceVariable.symbols)