python合法的布尔表达式_用列表表示布尔表达式的python

您可以让最外层的list表示“OR all direct entries”,然后在OR和and direct条目之间交换嵌套列表的含义。如果从最外层开始计算嵌套级别为1,则奇数嵌套级别中的项应为OR'd,偶数嵌套级别中的项应为and'd。在

所以ABC+DE(FG+IH)

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

下面是一些Python代码:

它从列表形式返回一个表达式:def to_bool(lst, depth=0, or_them=True):

if type(lst) == str:

return lst

else:

partial = ( '+' if or_them else ''

).join( to_bool(x, depth+1, not or_them) for x in lst)

if or_them and depth > 0:

# Mixture of variables and sublists so parenthesize

return '(' + partial + ')'

else:

return partial

def main():

A,B,C,D,E,F,G,H,I = 'ABCDEFGHI'

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

print('The list form of the boolean expression:', e)

print('The boolean expression:', to_bool(e))

if __name__ == '__main__':

main()

其输出:

^{pr2}$

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值