-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparen_bracket_check.py
More file actions
31 lines (26 loc) · 889 Bytes
/
Copy pathparen_bracket_check.py
File metadata and controls
31 lines (26 loc) · 889 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def check_parenthesis_balance(str):
open_list = ["[","{","("]
close_list = ["]","}",")"]
stack = []
for i in str:
if i in open_list:
stack.append(i)
elif i in close_list:
pos = close_list.index(i)
# find corresponding open element
open_element = open_list[pos]
# open element is at the top of stack
if len(stack) > 0 and stack[len(stack)-1] == open_element:
stack.pop()
else:
return "unbalanced"
break
if len(stack) == 0:
return "balanced"
def main():
expression = "{[]{()}}"
print("{0} is {1}".format(expression,check_parenthesis_balance(expression)))
expression = "[{}{})(]"
print("{0} is {1}".format(expression,check_parenthesis_balance(expression)))
if __name__ == "__main__":
main()