need some regular expression help

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Sun Oct 8 06:08:30 EDT 2006


Tim Chase:
> It still doesn't solve the aforementioned problem
> of things like ')))((('  which is balanced, but psychotic. :)

This may solve the problem:

def balanced(txt):
    d = {'(':1, ')':-1}
    tot = 0
    for c in txt:
        tot += d.get(c, 0)
        if tot < 0:
            return False
    return tot == 0

print balanced("42^((2x+2)sin(x)) + (log(2)/log(5))") # True
print balanced("42^((2x+2)sin(x) + (log(2)/log(5))") # False
print balanced("42^((2x+2)sin(x))) + (log(2)/log(5))") # False
print balanced(")))(((") # False

A possibile alternative for Py 2.5. The dict solution looks better, but
this may be faster:

def balanced2(txt):
    tot = 0
    for c in txt:
        tot += 1 if c=="(" else (-1 if c==")" else 0)
        if tot < 0:
            return False
    return tot == 0

Bye,
bearophile




More information about the Python-list mailing list