On Wed, Jul 20, 2011 at 12:29 AM, jmfauth <wxjmfa...@gmail.com> wrote: >> Then it is hard to code precisely. >> > > Not really. The trick is to count the different opener/closer > separately. > That is what I am doing to check balanced brackets in > chemical formulas. The rules are howerver not the same > as in math.
I think the difficulty is not in the algorithm, but in adhering to the desired output when it is ambiguously described. > But, if I want to parse a string from right to left, > what's the trick? > The best I found so far: > >>>> s = 'abcd' >>>> for i, c in enumerate(reversed(s)): > ... print len(s) - 1 - i, c That violates DRY, since you have reversal logic in the iterator algebra and then again in the loop body. I prefer to keep all such logic in the iterator algebra, if possible. This is one possibility, if you don't mind it building an intermediate list: >>> for i, c in reversed(list(enumerate(s))): ... Otherwise, here's another non-DRY solution: >>> from itertools import izip >>> for i, c in izip(reversed(xrange(len(s))), reversed(s)): ... Unfortunately, this is one space where there just doesn't seem to be a single obvious way to do it. -- http://mail.python.org/mailman/listinfo/python-list