我正在尝试弄清楚如何将带括号的布尔表达式展平为一组逻辑上相同的有序表达式
假设我有一个这样的表达式:
((((e1) or (e2)) and (e3 or (e5 and e6)) and (e7)) or (e8))
我需要最终得到一个表达式列表(e1、e2、e3 等)后跟和/或运算符,以便从左到右评估列表会产生相同的逻辑布尔答案。
即e1或e2和e5和e6或e3和e7或e8。但这不是正确的答案,但这是我最终需要得到的结果。
我知道递归下降解析器将计算表达式,但这不是我需要的,我需要最终得到一个可以稍后从左到右计算的表达式列表。
我想把它放在二叉树中,然后导航树后缀或类似的东西,但这似乎不对。
我曾经足够聪明,能够弄清楚这样的事情,但现在我有了孩子,失去了所有更高的认知能力。帮助?
So let's say I've got an expression like this:
((((e1) or (e2)) and (e3 or (e5 and e6)) and (e7)) or (e8))
I need to end up with a list of expressions (e1, e2, e3 etc) followed by and/or operators so that evaluating the list from left to right yields the same logical boolean answer.
ie e1 or e2 and e5 and e6 or e3 and e7 or e8. But that's not the right answer, but that's the kind of thing I need to end up with.
I know a recursive descent parser will evaluate the expression, but that's not what I need, I need to end up with a list of expressions that can be evaluated later left to right.
I was thinking put it in a binary tree and then navigate the tree postfix or something like that, but that doesn't seem right to be.
I used to be smart enough to figure out things like this, but now I have a baby and have lost all of my higher cognitive abilities. Help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您要做的是将中缀表示法转换为后缀表示法。
您对解析器的想法是正确的,因为您确实需要解析(但不评估)原始表达式,然后以后缀表示法将其打印出来。
First off, what you are looking to do is convert infix notation to postfix notation.
You are on the right track with your thoughts about a parser, for indeed you need to parse (but not evaluate) the original expression, and then print it out in postfix notation.
我的父亲有着近乎无限的智慧(尽管有两个孩子),他指出了一个相当简单的解决方案:
德摩根定律规定,您可以重写任何表达式,仅使用 AND 或 OR 以及 NOT 的各种用途。因此,只需将所有 AND 表达式转换为其等效的 OR 表达式,删除括号,然后从左到右求值即可。
非常可行的想法,除了在我的例子中 NOT 操作非常昂贵。
My dad with his near infinite intelligence (despite having 2 kids) points out a rather simple solution:
demorgan's law says you can rewrite any expression to use only ANDs or ORs with various uses of NOT. So simply convert all of the AND expressions to their OR equivalent, remove the parenthesis, and evaluate left to right.
Very workable idea, except that in my case the NOT operation is terribly expensive.