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
|
TOKENS = (('(', ')'), ('[', ']'), ('{', '}'))
def count_tokens(st, op, cl):
tkn = {op: 1, cl: -1}
count = 0
for idx, ch in enumerate(st):
if ch in (op, cl):
count += tkn[ch]
if count == -1:
raise SyntaxError("Unvalid token column %s" % idx)
return count
# On teste ça
strs = ['[[{aa[[aa(}}]]aa())]]', '{(ee[ee){(]}}', '[(dd[[d((]d{(()}))))]', '[[]]))))))']
for st in strs:
print('\n%s' % st)
for t in TOKENS:
try:
c = count_tokens(st, t[0], t[1])
except SyntaxError as why:
print("Error with %s : %s" % (t, why))
continue
else:
print('Conteneurs %s appariés: %s' % (t, not c)) |
Partager