简体   繁体   English

需要一种算法将命题逻辑表达式从中缀转换为后缀

[英]Need an algorithm to convert propositional logic expression from infix to postfix

I need an algorithm to convert propositional logic expressions from infix to postfix so that I can then convert them into expression trees. 我需要一种算法将命题逻辑表达式从中缀转换为后缀,以便随后将它们转换为表达式树。 Here are some examples of propositional logic expressions I am working with. 这是我正在使用的命题逻辑表达式的一些示例。

T Ť

((r^(~pvp))→(~pvp)) ((r ^(〜pvp))→(〜pvp))

(Tv~((p^(~qvq)))) (电视〜((p ^(〜qvq))))

Converting infix to postfix for arithmetic expressions is a very standard data structures textbook problem. 将算术表达式的中缀转换为后缀是一个非常标准的数据结构教科书问题。 However, I haven't been able to find many resources on this type of conversion for propositional logic. 但是,在命题逻辑的这种类型的转换上,我还找不到很多资源。

I have tried using the algorithm provided in the following link 我尝试使用以下链接中提供的算法

https://www.geeksforgeeks.org/stack-set-2-infix-to-postfix/ https://www.geeksforgeeks.org/stack-set-2-infix-to-postfix/

The algorithm doesn't seem to work when I apply it to propositional logic expressions. 当我将其应用于命题逻辑表达式时,该算法似乎不起作用。 My code keeps popping an empty stack. 我的代码不断弹出一个空堆栈。 I think this might have to do with the fact that operations in propositional logic (unlike in arithmetic) don't have a precedence, so I am not sure how to handle this. 我认为这可能与以下事实有关:命题逻辑(与算术不同)中的运算没有优先级,因此我不确定该如何处理。 Also, I don't know if handling the NOT operator (~) should be a special case, as it is a unary operator where all the other operators are binary. 另外,我不知道处理NOT运算符(〜)是否应该是特例,因为它是一元运算符,其中所有其他运算符都是二进制的。

If someone could please recommend or describe an algorithm for converting infix propositional logic expressions into postfix, I would really appreciate it! 如果有人可以推荐或描述一种将中缀命题逻辑表达式转换为后缀的算法,我将不胜感激! Thanks so much. 非常感谢。

You just need to implement the correct parsing of the unary operator. 您只需要实现一元运算符的正确解析即可。

Given that you don't rely on precedence, but will always enclose binary infix operations in parentheses, the process can be simplified, as there is then no need for an explicit stack with operators; 假定您不依赖优先级,而是始终将二进制中缀运算括在括号中,则可以简化该过程,因为这样就不需要使用运算符的显式堆栈了。 the call stack will take care of their order. 调用堆栈将照顾他们的订单。

Here is how it could be coded: 这是它的编码方式:

def inToPostFix(s):
    def reject(what): # Produce a readable error
        raise SyntaxError("Expected {}, but got {} at index {}".format(
            what or "EOF", 
            "'{}'".format(tokens[-1]) if tokens else "EOF", 
            len(s) - len(tokens)
        ))

    get = lambda: tokens.pop() if tokens else ""
    put = lambda token: output.append(token)
    match = lambda what: tokens[-1] in what if tokens else what == ""
    expect = lambda what: get() if match(what) else reject(what)

    def suffix():
        token = get()
        term()
        put(token)

    def parens(): 
        expect("(")
        expression(")")

    def term():
        if match(identifier): put(get())
        elif match(unary): suffix()
        elif match("("): parens()
        else: expect("an identifier, a unary operator or an opening parenthesis");

    def expression(terminator):
        term()
        if match(binary): suffix()
        expect(terminator)

    # Define the token groups
    identifier = "abcdefghijklmnopqrstuwxyz"
    identifier += identifier.upper()
    unary = "~";
    binary = "^v→";
    tokens = list(reversed(s)) # More efficient to pop from the end
    output = [] # Will be populated during the parsing
    expression("") # Parse!
    return "".join(output)

Example call: 示例调用:

print(inToPostFix("(Tv~((p^(~qvq))))"))

Note that here parentheses may be omitted when they would wrap the whole expression. 注意,当括号将整个表达式包装起来时,可以省略括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM