-
Notifications
You must be signed in to change notification settings - Fork 0
/
balanced-brackets.py
65 lines (50 loc) · 2.15 KB
/
balanced-brackets.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
"""
Stacks: Balanced Brackets
https://www.hackerrank.com/challenges/ctci-balanced-brackets
"""
import unittest
def is_matched(expr):
pair_dict = {
'}': '{',
']': '[',
')': '(',
}
stk = []
for item in expr:
if item in ['{', '[', '(']:
stk.append(item)
else:
if len(stk) == 0:
return False
prev = stk.pop(-1)
if pair_dict[item] != prev:
return False
if len(stk) > 0:
return False
return True
if __name__ == '__main__':
t = int(input().strip())
for a0 in range(t):
expression = input().strip()
if is_matched(expression) is True:
print("YES")
else:
print("NO")
class TestBalancedBrackets(unittest.TestCase):
def test_is_matched(self):
self.assertEqual(
True,
is_matched("{[()]}")
)
self.assertEqual(
False,
is_matched("{[(])}")
)
self.assertEqual(
True,
is_matched("{{[[(())]]}}")
)
self.assertEqual(
True,
is_matched("{()[[[]]({{}[{}]}){((()))([[]]([]{}[]{{()({})[{(())[]}]([{[]}])}()[][[]]()[([{{{(){[[(()(([()]([][]()()){[{}][((()[()])[{(([([]{({})})](){[]{}[[[][{{{}{[()]{[]{}}}(())}}]()[{}{}{[[]][[]{{()}}]}{([[[]]({[]})]{}){}}][[{[()]}]][]{}]{}()]{}})([])){}}[{}[]]{}]){[{}]{{{}[()](){}}[[{}]]{[{}]}{}()([]){}[][]}([]((){[][]{[({{}}[[[][()]][[][]]{}]){[][[]()]{}}[]]({}[{(([[]()](){((({()(){([])()[{{[[{}][]]}(){}[][][[]{}[]{{[(([{}]))]()[]}(())}][([])[{(())}](())[]([[([])]])]}]}}({}{}))))}){{}}(({()}){})[](([]()()[{([]){}(){(({}[]))}}()](()){{}{}}){({})}[[([[]()][])()[]]()])(()))}])()}{({()})(([[]]{()}[]))}})()(){[]})()[{{{}}[]}{}{}[][(({}[[{}(){}]]){{[[]{[{(()[])((([[]])((())))){}[][]}]({})}(())]}{}((){{}((){[[][]]}([]){({}[[]({}{}){}])}(){})}(()))[]}({([][])})()){}]]}{(){}}()]{[]}{}[]{}{{}{}}[{}{{()}}]({(){[]}({}[]()[])({}{{{[]{{}}}{}[][{}[]][][]}[{{()}()[{}[]]{}([]())}]})[]({[]})})[]}{(())[[]]})[](){[[]{}]{}({{}(){[]}}[]{{}[[][]][]()}){{}}})[(()[])[()[[{}()]()]()[]]])][[]({([{{}}])})]]}}}}])]}))}]}")
)