File tree Expand file tree Collapse file tree 1 file changed +21
-0
lines changed
Stack Algorithms/Balanced Parenthesis Problem/Python Expand file tree Collapse file tree 1 file changed +21
-0
lines changed Original file line number Diff line number Diff line change
1
+ def balanced (string ):
2
+ opening_parens = [ '(' , '[' , '{' ]
3
+ closing_parens = [ ')' , ']' , '}' ]
4
+ parens_dict = dict (zip (opening_parens , closing_parens ))
5
+
6
+ stack = []
7
+ for char in string :
8
+ if char in opening_parens :
9
+ stack .append (char )
10
+ elif char in closing_parens :
11
+ if not stack or char != parens_dict [stack .pop ()]:
12
+ return False
13
+ return not stack
14
+
15
+ if __name__ == '__main__' :
16
+ balanced_expression = '{[()()[]{}((()))]}'
17
+ print balanced (balanced_expression )
18
+ imbalanced_expression = '{[()()[]{}((()))]}}'
19
+ print balanced (imbalanced_expression )
20
+ invalid_expression = '{[()()[]{}((()))]}}{'
21
+ print balanced (invalid_expression )
You can’t perform that action at this time.
0 commit comments