-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
44 lines (35 loc) · 1.07 KB
/
main.py
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
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'isBalanced' function below.
#
# The function is expected to return a STRING.
# The function accepts STRING expression as parameter.
#
openParenthesis=["(", "{", "["]
closeParenthesis=[")", "}", "]"]
def isBalanced(expression):
stack=[]
for i in expression:
if i in openParenthesis:
stack.append(i)
elif i in closeParenthesis:
position=closeParenthesis.index(i)
if ((len(stack)>0) and (openParenthesis[position]==stack[len(stack)-1])): #if stack is not empty and the top element in the stack is the matching open parenthesis for the current closed parenthesis in the loop
stack.pop()
else:
return "NO"
if len(stack)==0:
return "YES"
else:
return "NO"
string = "{[]{()}}"
print(string,"-", isBalanced(string))
string = "[{}{})(]"
print(string,"-", isBalanced(string))
string = "((()"
print(string,"-",isBalanced(string))