the python way?
Andrew Dalke
dalke at dalkescientific.com
Mon Jun 6 16:46:38 EDT 2005
Reinhold Birkenfeld wrote:
> To make it short, my version is:
>
> import random
> def reinterpolate2(word, vocals='aeiouy'):
> wlist = list(word)
> random.shuffle(wlist)
> vees = [c for c in wlist[::-1] if c in vocals]
> cons = [c for c in wlist[::-1] if c not in vocals]
Why the [::-1]? If it's randomly shuffled the order isn't important.
> short, long = sorted((cons, vees), key=len)
> return ''.join(long[i] + short[i] for i in range(len(short))) + ''.join(long[len(short):])
All the cool kids are using 2.4 these days. :)
Another way to write this is (assuming the order of characters
can be swapped)
N = min(len(short), len(long))
return (''.join( [c1+c2 for (c1, c2) in zip(cons, vees)] +
cons[N:] + vees[N:])
The main change here is that zip() stops when the first iterator finishes
so there's no need to write the 'for i in range(len(short))'
If the order is important then the older way is
if len(cons) >= len(vees):
short, long = vees, cons
else:
short, long = cons, vees
return (''.join( [c1+c2 for (c1, c2) in zip(short, long)] +
long[len(short):])
'Course to be one of the cool kids, another solution is to use the
roundrobin() implementation found from http://www.python.org/sf/756253
from collections import deque
def roundrobin(*iterables):
pending = deque(iter(i) for i in iterables)
while pending:
task = pending.popleft()
try:
yield task.next()
except StopIteration:
continue
pending.append(task)
With it the last line becomes
return ''.join(roundrobin(short, long))
Anyone know if/when roundrobin() will be part of the std. lib?
The sf tracker implies that it won't be.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list