On Jul 14, 11:08 pm, David Smith <d...@cornell.edu> wrote: > Jeremy Sanders wrote: > > candide wrote: > > >> I'm trying to implement in Python a function testing if an expression is > >> well parenthesized. For instance the expression "zx4er(1(er(Yy)ol)ol)ik" > >> is correctly parenthesized but this one "zx(4er(1(er(Yy)ol)ol)ik" is not. > > >> My code follows at the end. > > >> If you have a better algorithm or a better Python code (I'm a beginner in > >> the Python world), don't hesitate ... > > > Don't you want to just test that the number of "("s equals the number of > > ")"s or am I missing the point? > > >>>> a='aAAA(bbb(cc)))' > >>>> a.count('(') == a.count(')') > > > Jeremy > > Using straight counting, )z))ab(c(ew( would be well parenthesized. I > suspect a better way would be to iterate over the string using a balance > counter that increases 1 for every open, decreases 1 for every close. A > negative balance at any moment would indicate an error as well as an > ending balance greater than 0. > > --David
Ummm isn't that the OP's first function? -- http://mail.python.org/mailman/listinfo/python-list