-
Notifications
You must be signed in to change notification settings - Fork 3
/
Balanced_braces.py
66 lines (60 loc) · 1.71 KB
/
Balanced_braces.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
'''
Input Format
The first line contains a single integer, n, denoting the number of strings.
Each line i of the n subsequent lines consists of a single string,s, denoting a sequence of brackets.
'''
#!/bin/python3
import math
import os
import random
import re
import sys
def braces(values):
ans = []
for index in values:
stack = []
flag = 0
for i in index:
if i == "(" or i == "[" or i == "{":
stack.append(i)
else:
if i == ")":
if len(stack) != 0 and stack[-1] == "(":
stack.pop()
else:
ans.append("NO")
flag = 1
break
elif i == "}":
if len(stack) != 0 and stack[-1] == "{":
stack.pop()
else:
ans.append("NO")
flag = 1
break
elif i == "]":
if len(stack) != 0 and stack[-1] == "[":
stack.pop()
else:
ans.append("NO")
flag = 1
break
else:
ans.append("NO")
flag = 1
break
if len(stack) == 0 and flag != 1:
ans.append("YES")
else:
if flag == 0:
ans.append("NO")
return ans
if __name__ == '__main__':
t = int(input())
x = []
for t_itr in range(t):
expression = input()
x.append(expression)
ans = braces(x)
ans = "\n".join(ans)
print(ans)