 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements
 