Re: How smart is the Python interpreter?
- From: Gary Herron <gherron@xxxxxxxxxxxxxxxxxx>
- Date: Thu, 31 Jul 2008 09:16:16 -0700
ssecorp wrote:
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?
--
http://mail.python.org/mailman/listinfo/python-list
The 'for' statement is only executed once of course. It's the body of the 'for' which is executed multiple times. So in both pieces of code, the 'sorted' is only executed once, and the returned string is bound to a name in the second but not the first.
However, you are worrying about optimizing the wrong things here. The 's+=a' line has terrible (quadratic) performance. Instead use the string method 'join' which has linear performance.
def str_sort(string):
return "".join(sorted(string))
No for loop, no inefficient accumulation.
Gary Herron
.
- References:
- How smart is the Python interpreter?
- From: ssecorp
- How smart is the Python interpreter?
- Prev by Date: Re: current week / weeks in year - best practice
- Next by Date: Re: Non Continuous Subsequences
- Previous by thread: Re: How smart is the Python interpreter?
- Next by thread: current week / weeks in year - best practice
- Index(es):
Relevant Pages
|