-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc3_stack_parenthesis.py
100 lines (89 loc) · 2.02 KB
/
c3_stack_parenthesis.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
94
95
96
97
98
99
100
from pythonds.basic import Stack
# 从list发展出stack
# class Mystack():
# def __init__(self):
# self.items = []
#
# def myisEmpty(self):
# return self.items == []
#
# def mysize(self):
# return len(self.items)
#
# def mypop(self):
# return self.items.pop()
#
# def mypush(self, value):
# return self.items.append(value)
#
# def mypeek(self):
# return self.items[-1]
#
#
# s = Mystack()
# s.mypush(1)
# s.mypush(True)
# s.mypush('good')
# print(s.items)
# print(s.mypeek(), s.mypop(), s.items, s.myisEmpty(), s.mysize(), sep=' ~~ ')
# # 括号的匹配
# def parenthesis_check(par):
# s = Stack()
# match = True
# i = 0
# while i < len(par) and match:
# if par[i] == '(':
# s.push(par[i])
# else:
# if s.isEmpty():
# match = False
# else:
# s.pop()
# i = i + 1
# if not s.isEmpty():
# match = False
# print(match)
# return match
#
#
# test = '((())())'
# parenthesis_check(test)
# # 括号的匹配 -- advanced
def basic_check(left, right):
a, b = '([{', ')]}'
# return a.index(left) == b.index(right)
done = False
if a.index(left) == b.index(right):
done = True
return done
#
def parenthesis_check(par):
s = Stack()
a, b = '([{', ')]}'
match = True
i = 0
while i < len(par) and match:
if par[i] in a:
s.push(par[i])
else:
if s.isEmpty():
match = False
elif not basic_check(s.peek(), par[i]):
match = False
else:
s.pop()
# else: #
# top=pop() #
# if not basic_check(top, par[i]):
# match = False
i = i + 1
if not s.isEmpty():
match = False
# if match and s.isEmpty():
# match = True
# else:
# match = False
print(match)
return match
test = '({[(())()]})'
parenthesis_check(test)