Re: How smart is the Python interpreter?



Am Donnerstag, 31. Juli 2008 13:09:57 schrieb ssecorp:
def str_sort(string):
s = ""
for a in sorted(string):
s+=a
return s


if i instead do:

def str_sort(string):
s = ""
so = sorted(string)
for a in so:
s+=a
return s


will that be faster or the interpreter can figure out that it only has
to do sorted(string) once? or that kind of cleverness is usually
reserved for compilers and not interpreters?

In a statement of the form

for <name> in <iterable>:

the expression <iterable> will only be evaluated once (to retrieve an
iterator), so basically, both ways of stating it are equivalent and make
negligible difference in runtime (the second version will be slower, because
you have additional code to assign/fetch a local).

Anyway, if you care about speed, probably:

def str_sort(string):
return "".join(sorted(string))

will be the fastest way of stating this.

--
Heiko Wundram
.



Relevant Pages

  • syntax error, unexpected kOR
    ... strange behaviour I found: ... def dummy? ... I agree that the interpreter is not able to undestand this one: ...
    (comp.lang.ruby)
  • Re: problem mixing gettext and properties
    ... Python interpreter. ... Therefore you get a name clash with _as an alias for gettext(). ... def switch_language: ... into one "master" module and have the other modules import that: ...
    (comp.lang.python)
  • Re: I get error with PFB and PFM files
    ... ....I have modifications to PFB file. ... Again this is correctly interpreted by PS interpreter but ATM fails. ... /FontName/Arial def ...
    (comp.lang.postscript)
  • Re: Class variables, instance variables, singleton; Ruby v.
    ... def sub1 ... Didn't the interpreter "see" @@x in class F? ... MLK> Probably not, since you haven't called the function yet! ... DM> class Foo ...
    (comp.lang.ruby)
  • Re: I get error with PFB and PFM files
    ... ....I have modifications to PFB file. ... Again this is correctly interpreted by PS interpreter but ATM fails. ... /FontName/Arial def ...
    (comp.lang.postscript)