String Splitter Brain Teaser

Michael Spencer mahs at
Mon Mar 28 20:38:37 CEST 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 = [[1]] #push the first char into the stack
>     for i,c in e:
>         if c != '/':
>             yield stack
>             stack = [c]
>         else:
>             stack.append([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 = []
     for i in srciter:
         if i == '/':
             yield item
             item = [i]
     yield item


More information about the Python-list mailing list