-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsymbalance.py
41 lines (35 loc) · 1.08 KB
/
symbalance.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
#
# Balanced tokens checker
# More general solution than http://interactivepython.org/runestone/static/pythonds/BasicDS/SimpleBalancedParentheses.html
# $Id$
__author__ = "Makhtar Diouf"
symbols = {'{': '}', '(': ')', '[': ']'}
def isbalanced(_target):
# Opening
ostack = list()
# Matching closing symbol
cstack = list()
for s in list(_target):
# Ignore characters not in the table
if s in symbols:
ostack.append(s)
elif s in symbols.values():
cstack.append(s)
#print(ostack, cstack)
if len(ostack) == len(cstack):
i = 0
for s in ostack:
print(s, symbols[s])
if not (ostack.count(s) == cstack.count(symbols[s])):
return False
elif ostack.index(s, i) == cstack.index(symbols[s], i):
print("Match: ", s, symbols[s])
#break #continue
else:
return False
i += 1
return True
return False
print(isbalanced('((([abc])))'))
print(isbalanced('ac(()'))
print(isbalanced(')xya('))