By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
 445,645 Members | 1,048 Online
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,645 IT Pros & Developers. It's quick & easy.

the python way?

 P: n/a 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][l10: 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 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
Share this Question
10 Replies

 P: n/a 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]][l10: 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][l10: 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

 P: n/a 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][l10: 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

 P: n/a 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][l10: 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

 P: n/a 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

 P: n/a 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

 P: n/a 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

 P: n/a 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

 P: n/a Doh! The ifilter() and ifilterfalse() calls should be swapped in the previous post. Jul 19 '05 #9

 P: n/a 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

 P: n/a On Mon, 06 Jun 2005 14:52:04 -0400, rumours say that Kent Johnson might have written: def newZip(a1,a2): """ reassemble """ l1=len(a1) l2=len(a2) longest, shortest = [[a1,a2], [a2,a1]][l1 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 discussion thread is closed

Replies have been disabled for this discussion.