Given a string str representing a logical expression which consists of the operators | (OR) , & (AND) , ! (NOT) , 0 , 1 and , only (i.e. no space between characters). The task is to print the result of the logical expression.
Input: str = “[[0,&,1],|,[!,1]]”
Input: str = “[!,[[0,&,[!,1]],|,[!,[[!,0],&,1]]]]”
- Start traversing the string from the end.
- If [ found go to Step-3 otherwise push the characters into the stack.
- Pop characters from stack until the stack top becomes “]”. > Insert each popped character into the vector.
- If the stack top becomes ] after 5 pop operations then the vector will be x, |, y or x, &, y.
- If the stack top becomes ] after 3 pop operations then the vector will be !, x.
- Pop ] from the stack top.
- Perform the respective operations on the vector elements then push the result back into the stack.
- If string is fully traversed then return the value at stack top otherwise go to step 2.
Below is the implementation of the above approach:
# Python3 program to solve the
# logical expression.
import math as mt
# Function to evaluate the logical expression
arr = list()
# traversing string from the end.
n = len(string)
for i in range(n – 1, -1, -1):
if (string[i] == “[“):
s = list()
while (arr[-1] != “]”):
# for NOT operation
if (len(s) == 3):
if s == “1”:
# for AND and OR operation
elif (len(s) == 5):
a = int(s) – 48
b = int(s) – 48
c = 0
if s == “&”:
c = a & b
c = a | b
arr.append((c) + 48)
# Driver code
# This code is contributed
# by mohit kumar 29
Time Complexity : O(n) Here, n is length of string.
- Evaluate a boolean expression represented as string
- Find all the patterns of "1(0+)1" in a given string | SET 2(Regular Expression Approach)
- Check if a string contains only alphabets in Java using Lambda expression
- Check if a binary string has a 0 between 1s or not | Set 2 (Regular Expression Approach)
- Check if a given string is a valid number (Integer or Floating Point) in Java | SET 2 (Regular Expression approach)
- Logical vs Physical Address in Operating System
- How to solve RSA Algorithm Problems?
- Solve the Crossword Puzzle
- Program to solve the Alligation Problem
- Expression Evaluation
- Expression contains redundant bracket or not
- Balanced expression with replacement
- Arithmetic Expression Evalution
- Find if an expression has duplicate parenthesis or not
- Stack | Set 4 (Evaluation of Postfix Expression)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.