Iteration over recursion?
MTD
marc.t.davies at gmail.com
Tue Jun 20 08:54:05 EDT 2006
Hello all,
I've been messing about for fun creating a trial division factorizing
function and I'm naturally interested in optimising it as much as
possible.
I've been told that iteration in python is generally more
time-efficient than recursion. Is that true?
Here is my algorithm as it stands. Any suggestions appreciated!
from math import *
def factorize(x):
""" Return factors of x """
factors = []
lim = int(sqrt(x))
y = divmod(x,2)
if y[1] == 0: # x is even
factors = factors + [2] + factorize(y[0])
else: # x is odd
i = 3
while i <= lim:
y = divmod(x,i)
if y[1] == 0:
factors = factors + [i] + factorize(y[0])
i = lim+1
else:
i += 2
if factors == []: # necessary step for correct recursion
factors = [x]
return factors
More information about the Python-list
mailing list