I could use some help making this Python code run faster using only Python code.

Paul Hankin paul.hankin at gmail.com
Thu Sep 20 18:46:53 EDT 2007


On Sep 20, 10:59 pm, Python Maniac <raych... at hotmail.com> wrote:
> I am new to Python however I would like some feedback from those who
> know more about Python than I do at this time.
>
> def scrambleLine(line):
>     s = ''
>     for c in line:
>         s += chr(ord(c) | 0x80)
>     return s
>
> def descrambleLine(line):
>     s = ''
>     for c in line:
>         s += chr(ord(c) & 0x7f)
>     return s
> ...

Well, scrambleLine will remove line-endings, so when you're
descrambling
you'll be processing the entire file at once. This is particularly bad
because of the way your functions work, adding a character at a time
to
s.

Probably your easiest bet is to iterate over the file using read(N)
for some small N rather than doing a line at a time. Something like:

process_bytes = (descrambleLine, scrambleLine)[action]
while 1:
    r = f.read(16)
    if not r: break
    ff.write(process_bytes(r))

In general, rather than building strings by starting with an empty
string and repeatedly adding to it, you should use ''.join(...)

For instance...
def descrambleLine(line):
  return ''.join(chr(ord(c) & 0x7f) for c in line)

def scrambleLine(line):
  return ''.join(chr(ord(c) | 0x80) for c in line)

It's less code, more readable and faster!

--
Paul Hankin




More information about the Python-list mailing list