【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

  : 1019  

一、記憶化再帰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)