permuting letters and fairy tales

Bengt Richter bokr at oz.net
Sat Nov 13 02:56:06 EST 2004


On Sat, 13 Nov 2004 03:30:44 GMT, bokr at oz.net (Bengt Richter) wrote:
[...]
>>
>Don't know the speed, but this seems fairly self-documenting to me
>(with a little thought ;-):
>
> >>> import random
> >>> def messwith(s):
> ...     seqisalpha = False; seq = []
> ...     for c in s:
> ...         if c.isalpha() == seqisalpha: seq.append(c); continue
> ...         elif seqisalpha and len(seq)>3:
> ...             mid = seq[1:-1]
> ...             random.shuffle(mid)
> ...             seq[1:-1] = mid
> ...         yield ''.join(seq)
> ...         seq = [c]
> ...         seqisalpha = c.isalpha()
> ...     if seq: yield ''.join(seq)
> ...
> >>> def jumble(s): return ''.join(messwith(s))
> ...
> >>> jumble('This is an example. It has 7 words ;-)')
> 'This is an elmxape. It has 7 wrods ;-)'
>
Hum, didn't think enough ;-/

 >>> jumble('last is antidisestablishmentarianism')
 'last is antidisestablishmentarianism'
 >>> jumble('last is antidisestablishmentarianism')
 'lsat is antidisestablishmentarianism'

Bad logic. Needs a repeat of the elif test and suite before the last yield line ;-/
I kind of smelled that as I was posting, but was too lazy to identify the offensive
material ;-)

But it does bring up a general problem of final logic in an iter loop. ISTM it could
be useful to have an option not to raise StopIteration, but instead keep returning
a specified sentinel at the end, something like file.read returns '' repeatedly at EOF.
E.g., I could have used it like (untested, and impossible since no such iter option ;-):

def messwith(s):
    seqisalpha = False; seq = []
    next = iter(s, EOSEQ='').next
    while True:
        c = next()
        if c and c.isalpha() == seqisalpha: seq.append(c); continue
        elif seqisalpha and len(seq)>3:
            mid = seq[1:-1]
            random.shuffle(mid)
            seq[1:-1] = mid
        yield ''.join(seq)
        if not c: break
        seq = [c]
        seqisalpha = c.isalpha()

In the meanwhile, I don't like any of the workarounds, but maybe
I just need some real sleep ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list