[prev in list] [next in list] [prev in thread] [next in thread]
List: python-list
Subject: Re: I could use some help making this Python code run faster using
From: Paul Hankin <paul.hankin () gmail ! com>
Date: 2007-09-20 22:46:53
Message-ID: 1190328413.226577.206740 () k79g2000hse ! googlegroups ! com
[Download RAW message or body]
On Sep 20, 10:59 pm, Python Maniac <raych...@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
--
http://mail.python.org/mailman/listinfo/python-list
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic