forked from anumsh/Python-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbracket_validator.py
51 lines (41 loc) · 1.62 KB
/
bracket_validator.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
"""
You're working with an intern that keeps coming to you with JavaScript code that won't run because the braces, brackets, and parentheses are off. To save you both some time, you decide to write a braces/brackets/parentheses validator.
Let's say:
'(', '{', '[' are called "openers."
')', '}', ']' are called "closers."
Write an efficient function that tells us whether or not an input string's openers and closers are properly nested.
Examples:
"{ [ ] ( ) }" should return True
"{ [ ( ] ) }" should return False
"{ [ }" should return False
"""
def is_valid(code):
openers_to_closers = {
'(' : ')',
'{' : '}',
'[' : ']'
}
openers = frozenset(openers_to_closers.keys())
print "the operners are : ",openers
closers = frozenset(openers_to_closers.values())
print "the closers are :", closers
openers_stack = []
print "opener_new_stack----------",openers_stack
for char in code:
if char in openers:
print "the characters are :",char
openers_stack.append(char)
elif char in closers:
print "char in closers "
print openers_stack
if not openers_stack:
return False
else:
last_unclosed_opener = openers_stack.pop()
# if this closer doesn't correspond to the most recently
# seen unclosed opener, short-circuit, returning false
if not openers_to_closers[last_unclosed_opener] == char:
return False
return openers_stack == []
print is_valid("hdfhsj([{}])fdffjfghb")
print is_valid("hdfhsj([{]fdffjfghb")