Profiling this code shows the bulk of the time is spent on the log operation. Is there another way to write this in Python 3 for more efficiency? Replacing the loop with a list comprehension was actually less efficient and so was map because of lambdas.
def log_total(data):
total = 0.0
log = log(data)
for i in range(10000):
total += log/(i+1)
return total
Thanks!
I'd factor the log
out of your summation and cache your sum:
harmonic_series = sum(1. / i for i in range(1, 10001)) # Thanks, @mgilson
def log_total(data):
return log(data) * harmonic_series
You could also use PyPy to speed it up even more.
Can write with lambda
in on line, like this:
total = lambda data: log(data) * sum(1.0 / i for i in xrange(1, 10001))
I used Python 2.7.3
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.