Python code for testing well parenthesized expression

Martin P. Hellwig martin.hellwig at dcuktec.org
Tue Jul 14 09:14:48 EDT 2009


Martin P. Hellwig wrote:
> candide wrote:
> To add to your implementations; a readable version:
> 
> +++file parantheses.py+++
> """Parentheses Module Test"""
> 
> def parentheses_are_paired(input_string):
>     "Check if 'input_string' contains paired parentheses, if so return 
> True."
>     parenthesis_count = 0
>     parenthesis_open = '('
>     parenthesis_close = ')'
> 
>     for character in input_string:
>         if character == parenthesis_open:
>             parenthesis_count += 1
>         elif character == parenthesis_close:
>             parenthesis_count -= 1
> 
> 
>     if parenthesis_count == 0:
>         return(True)
>     else:
>         if parenthesis_count < 0:
>             error_text = 'More closing parantheses than opening ones'
> 
>         elif parenthesis_count > 0:
>             error_text = 'More opening parantheses than closing ones'
> 
>         raise(ValueError(error_text))
> 
> if __name__ == '__main__':
>     TEST_TRUE = 'zx4er(1(er(Yy)ol)ol)ik'
>     TEST_ERROR = 'zx(4er(1(er(Yy)ol)ol)ik'
> 
>     print(parentheses_are_paired(TEST_TRUE))
> 
>     try:
>         print(parentheses_are_paired(TEST_ERROR))
>     except(ValueError):
>         print(False)
> 
> ---file parantheses.py---
> 

However as Mr. Roggisch commented this wouldn't check if it is on the 
right spot, by moving the check that at any time you can not have more 
closing ones than opening ones within the loop you will get those 
exceptions too.

-- 
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'



More information about the Python-list mailing list