Expression contains redundant bracket or not | Function to check redundant brackets in a balanced expression ; create a stack of characters ; Iterate through the given expression ; if current character is close parenthesis ')   ; If immediate pop have open parenthesis ' ( ' duplicate brackets found ; Check for operators in expression ; Fetch top element of stack ; If operators not found ; append open parenthesis ' ( ' , ; operators and operands to stack ; Function to check redundant brackets ; Driver code
def checkRedundancy ( Str ) : NEW_LINE INDENT st = [ ] NEW_LINE for ch in Str : NEW_LINE INDENT if ( ch == ' ) ' ) : NEW_LINE INDENT top = st [ - 1 ] NEW_LINE st . pop ( ) NEW_LINE flag = True NEW_LINE while ( top != ' ( ' ) : NEW_LINE INDENT if ( top == ' + ' or top == ' - ' or top == ' * ' or top == ' / ' ) : NEW_LINE INDENT flag = False NEW_LINE DEDENT top = st [ - 1 ] NEW_LINE st . pop ( ) NEW_LINE DEDENT if ( flag == True ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT st . append ( ch ) NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def findRedundant ( Str ) : NEW_LINE INDENT ans = checkRedundancy ( Str ) NEW_LINE if ( ans == True ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Str = " ( ( a + b ) ) " NEW_LINE findRedundant ( Str ) NEW_LINE Str = " ( a + ( b ) / c ) " NEW_LINE findRedundant ( Str ) NEW_LINE Str = " ( a + b * ( c - d ) ) " NEW_LINE findRedundant ( Str ) NEW_LINE DEDENT