Python code for testing well parenthesized expression
Adrian Dziubek
adrian.dziubek at gmail.com
Tue Jul 14 08:59:51 EDT 2009
Strings are immutable, so your method of slicing one letter at time
will be building lots of them. That shouldn't hurt you here, but it
will when you hit a bigger problem. In the i() there should be "return
op == 0" on the end.
def well(expr):
mapping = {'(':1, ')':-1}
count = 0
for s in expr:
if s in mapping:
count += mapping[s]
if s < 0:
return False
return count == 0
def test_well():
examples = [
('zx4er(1(er(Yy)ol)ol)ik', True),
('x(x)x(x(x)xx(xx(x)x(x(x)xx)(xxxx))x(x(x)xx)(xxxx)x)(xxxx)',
True),
('a(ty(y(y(bn)))lokl)kl', True),
('xc(er(tgy(rf(yh)()uj)ki))', True),
('e', True),
('rf(tgt)juj)jkik(jun)', False),
('zx(4er(1(er(Yy)ol)ol)ik', False),
]
for expr, expected in examples:
assert well(expr) == expected
More information about the Python-list
mailing list