the python way?

Kent Johnson kent37 at tds.net
Mon Jun 6 14:52:04 EDT 2005


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---------------------------



More information about the Python-list mailing list