Please Critique

John Farrell jfarrell at mincom.com
Tue Dec 14 00:53:01 EST 1999


The basic algorithm is fine, but you put too much stuff in. For example,
naming the output file and opening it is completely unnecessary, as you
can use the shell's output redirection to do that for you. Also, when
dealing with strings, using indexes is clumsy compared to using the
string itself. In my code below, I use implicit indices (list[:x] means
list[0:x] and list[x:] means list[x:-1]) and destroy the line, rather
than fiddling with start, end and startKey. Also, Python does not require
you to close files (I guess it closes the file when the last reference
goes away), so I left that out. Your iteration to join the values of the
map together is a classical way of doing that sort of thing, but in
situations where I can see a simple transformation to be done to a list of
objects, I like to use map and lambda (or list comprehensions, when they
are in the language).

John

> import string
> screenfile = open('scracc.txt')
> newfile = open('scrnew.txt', "w")
> for line in screenfile.readlines():
>     mydict = {}
>     trimline = line[4:-1]
>     start = 0
>     length = len(trimline)
>     while start < length:
>         end = start + 4
>         startkey = start + 1
>         mydict[trimline[startkey:end]] = trimline[start:end]
>         start = end
>     sortkeys = mydict.keys()
>     sortkeys.sort()
>     mylist = []
>     for key in sortkeys:
>         mylist.append(mydict[key])
>     newline = line[0:4] + string.joinfields(mylist, "") + "\n"
>     newfile.write(newline)
> screenfile.close()
> newfile.close()

import string
for line in open('scracc.txt').readlines():
    userid = line[:4]
    line = line[4:]
    mydict = { }
    while len(line) >= 4:
        instruction = line[0]
        number = line[1:4]
        line = line[4:]
        mydict[number] = instruction
    sortkeys = mydict.keys()
    sortkeys.sort()
    fields = map(lambda x: mydict[x] + x, sortkeys)
    print userid + string.join(fields, '')

-- 
Dr John Farrell - Research Architect - Mincom Limited

This transmission is for the intended addressee only and is confidential
information. If you have received this transmission in error, please delete
it and notify the sender. The contents of this E-mail are the opinion of the
writer only and are not endorsed by Mincom Limited unless expressly stated
otherwise.
----
I don't suffer from stress.  I am a carrier.




More information about the Python-list mailing list