
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to check whether parentheses are balanced or not in Python
Suppose we have a string s consisting of parenthesis "(" and ")". We have to check whether the parentheses are balanced or not.
So, if the input is like s = "(()())(())", then the output will be True
To solve this, we will follow these steps −
- num_open := 0
- for each character c in s, do
- if c is same as ')', then
- if num_open < 0, then
- num_open := num_open - 1
- otherwise,
- return False
- otherwise,
- num_open := num_open + 1
- if num_open < 0, then
- if c is same as ')', then
- return inverse of num_open
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, s): num_open = 0 for c in s: if c == ')': if num_open < 0: num_open -= 1 else: return False else: num_open += 1 return not num_open ob = Solution() print(ob.solve("(()())(())"))
Input
"(()())(())"
Output
False
- Related Articles
- Program to check whether different brackets are balanced and well-formed or not in Python
- Check for balanced parentheses in Python
- Program to check whether a tree is height balanced or not in C++
- Program to check whether elements frequencies are even or not in Python
- Program to check whether two sentences are similar or not in Python
- Program to check whether two string arrays are equivalent or not in Python
- Program to check whether all leaves are at same level or not in Python
- Program to check whether domain and range are forming function or not in Python
- Program to check whether all palindromic substrings are of odd length or not in Python
- Program to check whether leaves sequences are same of two leaves or not in python
- Program to check whether given graph is bipartite or not in Python
- Program to check whether given password meets criteria or not in Python
- Python program to check whether a list is empty or not?
- Golang Program to Check Whether Two Matrices are Equal or Not
- Swift Program to Check Whether Two Matrices Are Equal or Not

Advertisements