python-用列表表示布尔表达式 [英] python - representing boolean expressions with lists

查看:118
本文介绍了python-用列表表示布尔表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用仅包含列表的Python产品乘积形式(SOP)来表示布尔表达式.

I'm trying to represent boolean expressions in sum of products form(SOP) in Python with only lists.

例如,我有布尔表达式

ABC+DE(FG+IH)

我需要找到一个与上述表达式等效的列表,因此通过读取列表或嵌套列表并遵循某些规则以读取列表,读取列表的程序/程序员将能够将其转换回布尔表达式.

I need to find a list equivalent of the expression above, so by reading the list or nested list and following certain rules to read the list, the program/programmer reading the list will be able to convert it back to the boolean expression.

我想到的一种方法是构造嵌套列表.遵循两个规则:

One way I thought of doing this is constructing nested lists. Two rules to follow:

    同一列表中的
  1. 元素进行与"操作
  2. 列表相互平行,然后进行或"运算.

因此对于上面的示例,它将转换为:

So for the example above, it will translate to:

[[A,B,C],[D,E,[[F,G],[I,H]]]]

但是这套规则在某些情况下会发生冲突.例如,给定[[E,F],[D,C]],它可以表示EF + DC或EFDC,因为[E,F]和[D,C]在同一列表中,因此应将它们相加,但列表是并行的,因此也应进行或"操作.

But this set of rules conflicts itself in some cases. For example, given [[E,F],[D,C]], it can either mean EF+DC or EFDC, as [E,F] and [D,C] are in the same list so they should be anded, but lists are parallel so they should be ORed too.

我觉得我需要在上述两个规则之间设置一些优先级,或者添加另一个规则以使其更加清晰.

I feel like I need to set some precedence between the 2 rules above, or add another rule to make it more clear.

欢迎任何想法或建议.同样,这不是家庭作业,只是一些娱乐. 在此先感谢!

Any thoughts or suggestions are welcome. Also it's not homework, just something for fun. Thanks in advance!!

推荐答案

您可以走LISPy路线,让每个列表中的第一项成为操作员.例如,您给的表达式

You could go the LISPy route and have the first item in each list be the operator. For example, the expression you gave

ABC+DE(FG+IH)

将成为

['or', ['and', A, B, C], ['and', D, E, ['or', ['and', F, G], ['and', I, H]]]]

考虑到哪些内容可读性强.干杯!

Which is pretty readable, considering. Cheers!

这篇关于python-用列表表示布尔表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆