crimes in Python

ztranger at my-deja.com ztranger at my-deja.com
Thu Mar 9 10:32:56 EST 2000


(Kragen Sitaker) wrote:
> It left me with several questions:
> - on a 2800-record file, the Python program took
8 seconds, while the
>   Perl program took 1.5.  Why?  (I tried
precompiling all the REs I'm
>   using in the loop; it took me down to 7.9.)

Well, REs are slower in Python. I can't find where
I read it, but Fredrik Lundh has tested the new re
module coming with Python 1.6 and it's much faster
than the current one. (Think it was about 10 times
as fast on some of the examples).

> - is there a way to print things out with
"print" without tacking trailing
>   spaces or newlines on?  Or is using
sys.stdout.write() the only way?

if you use a comma at the end of the print
statement, it doesn't output newlines.

print "Row 1",
print " Still on row 1"

to avoid spaces you could probably use
print "nospace" + "nospace" or
print "%s%s" % ("nospace","nospace") or
print string.joinfields(listofstrings,"")

> - What's the equivalent of the Perl idiom while
(<FH>) { }?  I tried
>   while line = sys.stdin.readline():, but Python
complained that the
>   syntax was invalid.  I guess an assignment is
a statement, not an
>   expression, so I can't use it in the while
condition.  I resorted to
>   cutting and pasting the readline() call
outside the top of the loop
>   and inside the bottom of the loop.

there is a module named fileinput which work
pretty much like while (<>) in perl.

import fileinput
for line in fileinput.input():
    process(line)

to supply your own filename, just use
for line in fileinput.input(filename)
instead. (filename can be a list of filenames).

I've read a couple of good articles about
performance lately, but I can't seem to find them
right now. A couple of hints: 1) profiler module.
2) sequence operations (and the string module)
instead of RE:s when possible. 3) a couple of
functions (map, filter...) creates c-loops which
can be faster than for/while loops. 4) Use built
ins. (Written in c, much faster than calling
Python code).

Hope this helps, I have only used Python for a
short while.

/Fredrik


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list