Search code examples
pythondictionaryreplaceprologpropositional-calculus

Python - dictionary with propositions (replace string values)


I have some dictionary e.g. of form:

my_dictionary = {'A': '¬(p)', 'B': '→(q, ∧(¬(p), ∨(y, z)))', 'Aim': ['p', '→(p, q)']}

Is their a simple way to replace all strings appearing in the dictionary values of form →(q, ∧(¬(p), ∨(y, z))) or →(p, q) by (q→(¬(p)∧(y∨z))) or (p→q)?


Solution

  • I found some solution by my own using some prolog:

    Prolog-file (called "logic.pl") has to contain the following code:

    :-op(800, fx, ~).
    :-op(801, xfy, ∧).
    :-op(802, xfy, ∨).
    :-op(803, xfy, →).
    :-op(804, xfy, ↔).
    
    
    m_Proposition_Binary_x_y(X ∨ Y, X, Y).
    m_Proposition_Binary_x_y(X ∧ Y, X, Y).
    m_Proposition_Binary_x_y(X → Y, X, Y).
    m_Proposition_Binary_x_y(X ↔ Y, X, Y).
    

    Now we can define some function:

    from pyswip import Prolog
    
    def normalize(collection):
        interface = Prolog()
        interface.consult("Prolog/logic.pl")
    
        if type(collection) is str:
            proposition = collection
            try:
                rest = list(interface.query(f"m_Proposition_Binary_x_y({proposition},A,B)".replace("'","")))[0]
                return f"({normalize(rest['A'])}{proposition[0]}{normalize(rest['B'])})"
            except:
                return proposition
        
        elif type(collection) is list:
            return [normalize(x) for x in collection]
        elif type(collection) is dict:
            old_dict = collection
            new_dict = {}
    
            for key in old_dict:
                new_dict[key] = normalize(old_dict[key])
    
            return new_dict 
    

    With that background its possible to normalize the dictionary very easy:

    my_dictionary = {'A': '~(p)', 'B': '→(q, ∧(~(p), ∨(y, z)))', 'Aim': ['p', '→(p, q)']}
    
    print(m_str.normalize(my_dictionary))
    

    Output:

    {'A': '~(p)', 'B': '(q→(~(p)∧(y∨z)))', 'Aim': ['p', '(p→q)']}
    

    Only problem, for some reason I cant use ¬ instead of ~ with pyswip library (Version: 0.2.11), cause with ¬ I get the curios error:

    U+ffffffac is not in range [U+0000; U+10ffff]
    

    whereby ¬ has unicode U+00AC ..