-
Notifications
You must be signed in to change notification settings - Fork 0
/
balancedparentheses.py
93 lines (80 loc) · 2.03 KB
/
balancedparentheses.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
"""
Task:
Balanced parentheses means that each opening symbol has a corresponding
closing symbol and the pairs of parentheses are properly nested. Write an
algorithm that will read a string of parentheses from left to right and
decide whether the symbols are balanced.
>>> is_balanced("(()()()())")
True
>>> is_balanced("(((())))")
True
>>> is_balanced("(()((())()))")
True
>>> is_balanced("((((((())")
False
>>> is_balanced("()))")
False
>>> is_balanced("(()()(()")
False
>>> is_balanced("{{([][])}()}")
True
>>> is_balanced("[{()]")
False
"""
# Version 1: Only check '(' and ')'
def is_balanced(str_):
stack = []
for char in str_:
if char == '(':
stack.append(char)
elif char == ')':
if not stack: # empty stack
return False
if stack[-1] == '(':
stack.pop()
else:
return False
else: # pass other characters
continue
# return true if stack is still empty
if stack:
return False
else:
return True
# Version 2: check "([{" and ")]}"
def is_balanced(str_):
stack = []
for char in str_:
if char in "([{":
stack.append(char)
elif char in ")]}":
if not stack: # empty stack
return False
top = stack[-1]
# check whether current char matches stack top
if matches(top, char):
stack.pop()
else:
return False
else: # pass other characters
continue
# balanced if stack is empty
if stack:
return False
else:
return True
def matches(char1, char2):
"""Check whether open and close parenthesis matches
>>> matches("(", ")")
True
>>> matches("[", "]")
True
>>> matches("{", ")")
False
"""
opens = "([{"
closes = ")]}"
return opens.index(char1) == closes.index(char2)
if __name__ == '__main__':
import doctest
doctest.testmod()