the python way?
Reinhold Birkenfeld
reinhold-birkenfeld-nospam at wolke7.net
Mon Jun 6 15:01:47 EDT 2005
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---------------------------
More information about the Python-list
mailing list