String Splitter Brain Teaser

Michael Spencer mahs at telcopartners.com
Mon Mar 28 13:38:37 EST 2005


Bill Mill wrote:
 > [long genomes might justify a generator approach]
That's a good point.  I should have said: *If* you are going to put the items 
into a list anyway, then there is no point generating the list items individually.

Michael Spencer wrote:
 >>[Bill's solution didn't work for multiple-degeneracies]
> This is simple enough to fix, in basically the same way your function
> works. I think it actually makes the function simpler:
> 
> def xgen(s):
>     e = enumerate(s)
>     stack = [e.next()[1]] #push the first char into the stack
>     for i,c in e:
>         if c != '/':
>             yield stack
>             stack = [c]
>         else:
>             stack.append(e.next()[1])
>     yield stack
> 
That is clearer.  At this point, though, you don't need the enumerator any more 
(so you can avoid indexing each item):

def xgen(s):
     srciter = iter(s)
     item = [srciter.next()]
     for i in srciter:
         if i == '/':
             item.append(srciter.next())
         else:
             yield item
             item = [i]
     yield item

Cheers
Michael




More information about the Python-list mailing list