[Tutor] How to improve

taserian taserian at gmail.com
Thu Jul 12 15:08:22 CEST 2007


I've been programming for years before encountering Pythoin, but in much
more verbose languages, and I appreciate the fact that Python is so terse
and still accomplishes so much. Still, I have difficulty thinking in Python,
and tend to revert to longer programs for what seems to be simple tasks.
Sometimes it's because I'm just not aware of a library function, but many
times it's because there's just some elegant way to solve my kludge.

As an exercise in Python, I decided to solve a toy problem called
"interleave". The idea is that I want to determine how many words in the
English language are decomposable into two words by taking it apart one
letter at a time. So the word "theorems" could be decomposed into "term" and
"hoes" (original word = abababab, decomposed words = aaaa and bbbb, with all
letters in the same order as in the original word).

I'd like to see how I could improve the program below for this, and make it
more Python-ish.

= = = = START

def decompose(longword):
    word1 = longword[0::2]
    word2 = longword[1::2]
    return (word1, word2)

wordlengthlist = [None] * 31
for i in range(0,len(wordlengthlist)):
    wordlengthlist[i] = []
results = []

for lineread in open("word.list"):
    for word in lineread.split():
        if len(word)<31:
            wordlengthlist[len(word)].append(word)

outfile = open('InterleaveEnglishYAWL.txt', 'w')

for x in range(4, 31):
    print x
    for i in wordlengthlist[x]:
        twowords = decompose(i)
        word1 = twowords[0]
        word2 = twowords[1]
        if     word1 in wordlengthlist[len(word1)] and word2 in
wordlengthlist[len(word2)]:
            outfile.write("(" + word1 + ", " + word2 + ", " + i + ")\n")
            print (word1, word2, i)

outfile.close();

= = = = END

Tony R.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070712/30841107/attachment.html 


More information about the Tutor mailing list