473,396 Members | 1,865 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

the python way?

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

Jul 19 '05 #1
10 1484
Grooooops wrote:
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---------------------------

Jul 19 '05 #2
Grooooops wrote:
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)
Jul 19 '05 #3
Grooooops wrote:
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[i] + short[i] 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.
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---------------------------

Jul 19 '05 #4
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
------------
x=["ohndes","j","wu","x[1][0]+x[0][:3]+chr(((len(x))*16))+x[2]+x[0][2:]+`round(1)`[1]+x[3][17]+x[0][0]+chr(ord(x[0][2])-1)"]
print eval(x[3])
------------

Jul 19 '05 #5
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
da***@dalkescientific.com

Jul 19 '05 #6
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")

Jul 19 '05 #7
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")

Jul 19 '05 #8
Doh!

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

Jul 19 '05 #9
Andrew Dalke wrote:
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.


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[i] + short[i] 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
Jul 19 '05 #10
On Mon, 06 Jun 2005 14:52:04 -0400, rumours say that Kent Johnson
<ke****@tds.net> might have written:
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.
--
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
Jul 19 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.