Language Shootout

Tim Peters tim.one at home.com
Wed Jul 11 23:52:59 EDT 2001


[Bengt Richter]
> I would guess the general purpose str already does something
> internally specialized for longs.

Yes it does.  Every type gets to implement its own routine for repr() (and
at the Python level, every class gets to implement its own too-- if it wants
to --via defining a __repr__ method, and/or a __str__ method).

> However, the % operator is even more general purpose, and you may
> note that I used it to trim my trees in strL (because it is faster
> than carrying strLR's recursion all the way down to w=1 and chr(48+n)).

And %d defers right back to the long repr routine!

> BDFL & Tim & co probably just had better things to do than cater
> to the small percentage of strange people with programs
> that need to convert longs to multi-kilo-digit integers ;-)

We *do* cater to it, but only in the power-of-2 forms:  hex(long) and
oct(long) are linear-time, and you're not going to beat those with Python
code.  For base 10, it's a dead-simple loop that just divides by 10 over and
over again; this is quadratic-time in the number of digits.

> I'm sure they know how to do this kind of thing very well,
> but if they think it's worth the seldom-used-bloat-increment,
> they're certainly welcome to take strL and make it truly
> Python-worthy and incorporate it.

The rub is that while this kind of thing is fun and easy to program in
Python, it's a total pain in the ass to program in C, and indeed leads to
code bloat.  Since Python longs use base 2**15 internally, converting to
power-of-2 bases is both simple and fast in C, so we settled for that.

Here's another fun one:  you can also write a long-int multiplication
routine in Python that runs significantly faster than the builtin long *!
Hint:  recursion <wink>.

You can even write Python routines to do str(dict) and str(list) much faster
than the builtins, for very large dicts and lists.  But you have to hurry on
those, because Python 2.2 will finally use linear-time algorithms for those
under the covers.

> (Maybe I'd find out how to keep everything but strL invisible from
> the user, and make strLR nested without triggering a warning ;-)

Use Python 2.1, nest the helper functions, and put

from __future__ import nested_scopes

at the top of the module.  Heh -- you probably think I'm kidding.

but-i'm-not-ly y'rs  - tim





More information about the Python-list mailing list