Python code for testing well parenthesized expression

John Machin sjmachin at lexicon.net
Tue Jul 14 09:14:50 EDT 2009


candide <candide <at> free.invalid> writes:

> # The obvious iterative version
> def i(s):
>     op = 0 # op : open parenthesis
>     for k in range(len(s)):
>         op += (s[k] == '(') - (s[k] == ')')
>         if op < 0: break
>     return op
> 

E: H c, w t P.
F: A c, b à P.

Suggested better code:

def iterative(string):
    paren_count = 0
    for char in string:
        paren_count += (char == '(') - (char == ')')
        if paren_count < 0: break
    return paren_count

You don't need the other versions :-)

Try an iterative version of checking that () [] and {}
are balanced and nested appropriately.

Cheers,
John




More information about the Python-list mailing list