What is the "functional" way of doing this?
Ricardo Aráoz
ricaraoz at gmail.com
Tue Jul 31 10:43:26 EDT 2007
Kept testing (just in case).
There was this other version of lists2.py (see below). So I created
lists3.py and lists4.py.
The resulting times are
lists1.py : 11.4529998302
lists2.py : 16.1410000324
lists3.py : 3.17199993134
lists4.py : 20.9839999676
lists3.py is by far the better time, but it does not generate a list but
a generator object, as soon as you make it into a list (lists4.py) times
go up (I don't know why do they go up that much). Apparently the way you
use the conversion to a list, in the function(lists2.py) or in the loop
(lists4.py), makes a big difference. Anyway lists1.py is still the best
of the list generating times, and (in my view) the most elegant and easy
to understand expression of the algorithm.
------------------------------------------------
lists1.py :
def f(n):
if n > 0:
return ([n%26] + f(n/26))
else:
return []
import time
start = time.time()
for x in range(1,1000000):
f(2100000000)
end = time.time()
print end - start
-----------------------------------------------
lists2.py :
def f(n):
def mseq(n):
while n > 0:
n,a = divmod(n, 26)
yield a
return list(mseq(n))
import time
start = time.time()
for x in range(1,1000000):
f(2100000000)
end = time.time()
print end - start
------------------------------------------------
lists3.py
def f(n):
if n>0:
yield n%26
for i in f(n/26):
yield i
import time
start = time.time()
for x in range(1,1000000):
f(2100000000)
end = time.time()
print end - start
------------------------------------------------
lists4.py
def f(n):
if n>0:
yield n%26
for i in f(n/26):
yield i
import time
start = time.time()
for x in range(1,1000000):
list(f(2100000000))
end = time.time()
print end - start
----------------------------------------------------
More information about the Python-list
mailing list