the python way?

G

Grooooops

Hi All,

I've been lurking the list for a month and this is my first post. I am
hoping this post is appropriate here, otherwise, my apologies.

I'm somewhat new to Python, (I'm reading all the tutorials I can find,
and have read through Andre Lessa's Developers Handbook.)
I am trying to learn the Python way of thinking as well as the syntax.

I popped this bit of code together for fun, based on a previous post
regarding randomizing a word.
This shuffles a word, then splits out the vowels and then reassembles
it with the vowels interpolated between consonants.
(To create plausible sounding gibberish)

The code just seems kind of bulky to me. I am wondering, is this an
efficient way to do things, or am I making things harder than
necessary?

#--------------------------begin code------------------
"""scrambles a word, but creates plausable gibberish"""
import random
def shuffled(s):
""" scrambles word"""
l = list(s)
random.shuffle(l)
return ''.join(l)

def contains(alist,b):
"""...is letter b in list a..."""
ret = []
for all in alist:
#print all
if all==b:
return 1
return 0

def newZip(a1,a2):
""" reassemble """
l1=len(a1)
l2=len(a2)

longest = [a1,a2][l1<l2]
shortest = [a1,a2][longest == a1]
diff = max(l1,l2)-min(l1,l2)
#print longest
seq = len(longest)
ret = ""
for j in range(seq):
if len(longest)>0:
ret = ret + longest.pop()
if len(shortest)>0:
ret = ret + shortest.pop()
return ret

def reinterpolate(word):
""" main function """
wlist = shuffled(list(word))
vlist = list('aeiouy') # ok, y isn't really a vowel, but...
vees = filter(lambda x: contains(vlist,x),wlist)
cons = filter(lambda x: not(contains(vlist,x)),wlist)
a=list(vees)
b=list(cons)
return newZip(a,b)

word = "encyclopedia"
print reinterpolate(word)

#-------------------------------end code---------------------------

BTW: I'm just curious, is there an easier way to copy-paste code
snippets from the interpreter so that it removes the '... ' and the
'>>> ' from the examples? I'm using <cntrl-H> search and replace now
which works, but if there is a better way, I'd like to know.

thanks in advance,
-J
 
K

Kent Johnson

Grooooops said:
The code just seems kind of bulky to me. I am wondering, is this an
efficient way to do things, or am I making things harder than
necessary?

Harder than necessary.
contains() is not needed at all, you can test for 'b in alist' directly.
List comprehensions simplify reinterpolate(), and you have a lot of redundant calls to list().

Here is a shorter version:

"""scrambles a word, but creates plausable gibberish"""
import random
def shuffled(s):
""" scrambles word"""
l = list(s)
random.shuffle(l)
return ''.join(l)


def newZip(a1,a2):
""" reassemble """
l1=len(a1)
l2=len(a2)

longest, shortest = [[a1,a2], [a2,a1]][l1<l2]
diff = max(l1,l2)-min(l1,l2)

seq = len(longest)
ret = ""
for j in range(seq):
if len(longest)>0:
ret += longest.pop()
if len(shortest)>0:
ret += shortest.pop()
return ret

def reinterpolate(word):
""" main function """
wlist = shuffled(word)
vlist = 'aeiouy' # ok, y isn't really a vowel, but...
vees = [ x for x in wlist if x in vlist ]
cons = [ x for x in wlist if x not in vlist ]
return newZip(vees,cons)

word = "encyclopedia"
print reinterpolate(word)

Kent
#--------------------------begin code------------------
"""scrambles a word, but creates plausable gibberish"""
import random
def shuffled(s):
""" scrambles word"""
l = list(s)
random.shuffle(l)
return ''.join(l)

def contains(alist,b):
"""...is letter b in list a..."""
ret = []
for all in alist:
#print all
if all==b:
return 1
return 0

def newZip(a1,a2):
""" reassemble """
l1=len(a1)
l2=len(a2)

longest = [a1,a2][l1<l2]
shortest = [a1,a2][longest == a1]
diff = max(l1,l2)-min(l1,l2)
#print longest
seq = len(longest)
ret = ""
for j in range(seq):
if len(longest)>0:
ret = ret + longest.pop()
if len(shortest)>0:
ret = ret + shortest.pop()
return ret

def reinterpolate(word):
""" main function """
wlist = shuffled(list(word))
vlist = list('aeiouy') # ok, y isn't really a vowel, but...
vees = filter(lambda x: contains(vlist,x),wlist)
cons = filter(lambda x: not(contains(vlist,x)),wlist)
a=list(vees)
b=list(cons)
return newZip(a,b)

word = "encyclopedia"
print reinterpolate(word)

#-------------------------------end code---------------------------
 
S

Steven Bethard

Grooooops said:
Hi All,

I've been lurking the list for a month and this is my first post. I am
hoping this post is appropriate here, otherwise, my apologies.

I'm somewhat new to Python, (I'm reading all the tutorials I can find,
and have read through Andre Lessa's Developers Handbook.)
I am trying to learn the Python way of thinking as well as the syntax.

I popped this bit of code together for fun, based on a previous post
regarding randomizing a word.
This shuffles a word, then splits out the vowels and then reassembles
it with the vowels interpolated between consonants.
(To create plausible sounding gibberish)

The code just seems kind of bulky to me. I am wondering, is this an
efficient way to do things, or am I making things harder than
necessary?

#--------------------------begin code------------------
"""scrambles a word, but creates plausable gibberish"""
import random
def shuffled(s):
""" scrambles word"""
l = list(s)
random.shuffle(l)
return ''.join(l)

def contains(alist,b):
"""...is letter b in list a..."""
ret = []
for all in alist:
#print all
if all==b:
return 1
return 0

"contains(alist, b)" can be more easily written as "b in alist"

def newZip(a1,a2):
""" reassemble """
l1=len(a1)
l2=len(a2)

longest = [a1,a2][l1<l2]
shortest = [a1,a2][longest == a1]

longest, shortest = sorted([a1, a2], key=len)
diff = max(l1,l2)-min(l1,l2)
#print longest
seq = len(longest)
ret = ""

Don't build up strings using +. Create a list of strings, and use
str.join at the end.
for j in range(seq):
if len(longest)>0:

The len() > 0 is unnecessary, simply use:

if longest:
ret = ret + longest.pop()
if len(shortest)>0:

if shortest:
ret = ret + shortest.pop()
return ret

If I understand you right, you want to do the usual thing zip does, but
guaraneeing that the first element is always from the longer list, and
not throwing away elements. Note that map(None, ...) probably does what
you want:

longest, shortest = sorted([a1, a2], key=len, reverse=True)
return ''.join(item
for pair in map(None, longest, shortest)
for item in pair
if item is not None)

def reinterpolate(word):
""" main function """
wlist = shuffled(list(word))
vlist = list('aeiouy') # ok, y isn't really a vowel, but...

no need to make vlist a list; contains should work fine on strings.
vees = filter(lambda x: contains(vlist,x),wlist)

vees = [c in vlist for c in wlist]
cons = filter(lambda x: not(contains(vlist,x)),wlist)

cons = [c not in vlist for c in wlist]
a=list(vees)
b=list(cons)

The above are unnecessary. vees and cons are already lists.
return newZip(a,b)

word = "encyclopedia"
print reinterpolate(word)

So I think overall, my rewrite of your code would look something like
(untested):

def reinterpolate(word)
wlist = list(word)
random.shuffle(wlist)
vlist = 'aeiouy'
vees = [c for c in wlist if c in vlist]
cons = [c for c in wlist if c not in vlist]
longest, shortest = sorted([vees, cons], key=len)
return ''.join(item
for pair in map(None, longest, shortest)
for item in pair
if item is not None)
 
R

Reinhold Birkenfeld

Grooooops said:
Hi All,

I've been lurking the list for a month and this is my first post. I am
hoping this post is appropriate here, otherwise, my apologies.

I'm somewhat new to Python, (I'm reading all the tutorials I can find,
and have read through Andre Lessa's Developers Handbook.)
I am trying to learn the Python way of thinking as well as the syntax.

I popped this bit of code together for fun, based on a previous post
regarding randomizing a word.
This shuffles a word, then splits out the vowels and then reassembles
it with the vowels interpolated between consonants.
(To create plausible sounding gibberish)

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]
short, long = sorted((cons, vees), key=len)
return ''.join(long + short for i in range(len(short))) + ''.join(long[len(short):])

The code just seems kind of bulky to me. I am wondering, is this an
efficient way to do things, or am I making things harder than
necessary?

Some comments on your code:
#--------------------------begin code------------------
"""scrambles a word, but creates plausable gibberish"""
import random
def shuffled(s):
""" scrambles word"""
l = list(s)
random.shuffle(l)
return ''.join(l)

You can define this function separately, but needn't.
def contains(alist,b):
"""...is letter b in list a..."""
ret = []
for all in alist:
#print all
if all==b:
return 1
return 0

That is entirely unnecessary - use "b in alist" :)
def newZip(a1,a2):
""" reassemble """
l1=len(a1)
l2=len(a2)

longest = [a1,a2][l1<l2]
shortest = [a1,a2][longest == a1]
diff = max(l1,l2)-min(l1,l2)

diff = abs(l2-l1) would be shorter.
#print longest
seq = len(longest)
ret = ""
for j in range(seq):
if len(longest)>0:
ret = ret + longest.pop()

ret += longest.pop() comes to mind.
if len(shortest)>0:
ret = ret + shortest.pop()
return ret

def reinterpolate(word):
""" main function """
wlist = shuffled(list(word))

shuffled() will make a list itself, so list() is superfluous here.
vlist = list('aeiouy') # ok, y isn't really a vowel, but...
vees = filter(lambda x: contains(vlist,x),wlist)

Use a list comprehension here, like above.
 
G

Grooooops

Wow... Thanks for all the tips guys...
I will study the above examples.

....down to 8 lines of exquisitely readable code... Wow... Python
rocks...


(still aspiring to greatness myself,)
cheers,
-John
 
A

Andrew Dalke

Reinhold said:
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 + short 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
(e-mail address removed)
 
R

Raymond Hettinger

import random
from itertools import ifilter, ifilterfalse

def reinterpolate(word):

word = list(word)
random.shuffle(word)

isvowel = dict.fromkeys('aeiouy').has_key
vowels = ifilterfalse(isvowel, word)
consonants = ifilter(isvowel, word)

result = []
for v, c in map(None, vowels, consonants):
if c:
result.append(c)
if v:
result.append(v)
return ''.join(result)

print reinterpolate("encyclopedias")
 
G

Greg McIntyre

I like this solution. For some reason it made me want to write a Ruby
version of it. Possibly something about the title and the fact that
Ruby enthusiasts are always going on about "the Ruby way".

VOWELS = 'aeiouy'.split('')

def reinterpolate(word)
letters = word.split('').sort_by{rand}
vowels = letters.find_all{|l| VOWELS.include?(l) }
consonants = letters - vowels
return vowels.zip(consonants).map{|v, c| "#{c}#{v}" }.join('')
end

puts reinterpolate("encyclopedias")
 
R

Raymond Hettinger

Doh!

The ifilter() and ifilterfalse() calls should be swapped in the
previous post.
 
R

Reinhold Birkenfeld

Andrew said:
Reinhold said:
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.

I wanted to keep compatibility with Groops' version so that I could test
that my one works right. Since he did list.pop() it was necessary.
short, long = sorted((cons, vees), key=len)
return ''.join(long + short for i in range(len(short))) + ''.join(long[len(short):])


All the cool kids are using 2.4 these days. :)


Yep, it's the best way to advertise for its cool features ;)


Reinhold
 
C

Christos TZOTZIOY Georgiou

def newZip(a1,a2):
""" reassemble """
l1=len(a1)
l2=len(a2)
longest, shortest = [[a1,a2], [a2,a1]][l1<l2]
<snip>

Other ways to write the last line:
----------------------------------

/a/ execution in 22.5% of the original time taken

longest, shortest = l1 < l2 and (a2,a1) or (a1,a2)


/b/ execution in 12.5% of the original time taken

if l1 < l2: longest, shortest= a2, a1
else: longest, shortest= a1, a2


/c/ execution in 6.5% of the original time taken

if l1 < l2: longest= a2; shortest= a1
else: longest= a1; shortest= a2


Another exotic way to write the last *three* lines, running in 228.7% of
the original time:)

shortest, longest=sorted([a1,a2], key=len)


Numbers from 2.4c1 on a Pentium-M running at 600 MHz (battery powered).
Suggestion /a/ has the advantage of no repetion of the names like the
original line.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,527
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top