【python】:布尔运算

给定一个布尔表达式和一个期望的布尔结果 result,布尔表达式由 0 (false)1 (true)& (AND)| (OR)^ (XOR) 符号组成。实现一个函数,算出有几种可使该表达式得出 result 值的括号方法。

示例 1:

输入: s = "1^0|0|1", result = 0

输出: 2
解释: 两种可能的括号方法是
1^(0|(0|1))
1^((0|0)|1)
示例 2:

输入: s = "0&0&0&1^1|0", result = 1

输出: 10
提示:

运算符的数量不超过 19

一、记忆化递归
lru_cache可以记录函数的调用结果。
根据结果分类:
result = 1: 0&0 + 0&1 + 1&0/0|0/ 1^1
result = 0: 1&1/1|1 + 0|1 + 1|0/1^ 0 + 0^1

Class Solution:
    AND = '&'
    OR = '|'
    XOR = '^'

    @lru_cache(None)
    def countEval(self, s: str, result: int) -> int:
        if len(s) <= 3:
            return int(eval(s) == result)
        
        res = 0
        for i in range(1, len(s), 2):
            symbol = s[i]
            if result == 0:
                if symbol == self.AND:
                    # 0&0 + 0&1 + 1&0
                    res += self.countEval(s[:i], 0)*self.countEval(s[i+1:], 0) + self.countEval(s[:i], 0)*self.countEval(s[i+1:], 1) + self.countEval(s[:i], 1)*self.countEval(s[i+1:], 0)
                elif symbol == self.OR:
                    # 0|0
                    res += self.countEval(s[:i], 0)*self.countEval(s[i+1:], 0)
                elif symbol == self.XOR:
                    # 0^0 + 1^1
                    res += self.countEval(s[:i], 0)*self.countEval(s[i+1:], 0) + self.countEval(s[:i], 1)*self.countEval(s[i+1:], 1)
            
            else:
                if symbol == self.AND:
                    # 1&1
                    res += self.countEval(s[:i], 1)*self.countEval(s[i+1:], 1)
                elif symbol == self.OR:
                    # 1|1 + 0|1 + 1|0
                    res += self.countEval(s[:i], 1)*self.countEval(s[i+1:], 1) + self.countEval(s[:i], 0)*self.countEval(s[i+1:], 1) + self.countEval(s[:i], 1)*self.countEval(s[i+1:], 0)
                elif symbol == self.XOR:
                    # 1^0 + 0^1
                    res += self.countEval(s[:i], 1)*self.countEval(s[i+1:], 0) + self.countEval(s[:i], 0)*self.countEval(s[i+1:], 1)

        return int(res)

你可能感兴趣的:(python算法,python,leetcode)