a little parsing challenge ☺

Robert Klemme shortcutter at googlemail.com
Wed Jul 20 08:23:09 CEST 2011


On 18.07.2011 16:39, Xah Lee wrote:
>
> On Jul 17, 12:47 am, Xah Lee<xah... at gmail.com>  wrote:
>> 2011-07-16
>>
>> folks, this one will be interesting one.
>>
>> the problem is to write a script that can check a dir of text files
>> (and all subdirs) and reports if a file has any mismatched matching
>> brackets.
>>>
> Ok, here's my solution (pasted at bottom). I haven't tried to make it
> elegant or terse, yet, seeing that many are already much elegent than
> i could possibly do so with my code.
>
> my solution basically use a stack. (i think all of us are doing
> similar) Here's the steps:
>
> • Go thru the file char by char, find a bracket char.
> • check if the one on stack is a matching opening char. If so remove
> it. Else, push the current onto the stack.
> • Repeat the above till end of file.
> • If the stack is not empty, then the file got mismatched brackets.
> Report it.
> • Do the above on all files.

Small correction: my solution works differently (although internally the 
regexp engine will roughly do the same).  So, my approach summarized

- traverse a directory tree
- for each found item of type "file"
-    read the whole content
-    throw it at a regexp which is anchored at the beginning
      and does the recursive parsing
-    report file if the match is shorter than the file

Note: special feature for recursive matching is used which Perl's regexp 
engine likely can do as well but many others don't.

Cheers

	robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/




More information about the Python-list mailing list