[Tutor] exercise is recursion

Moshe Zadka Moshe Zadka <moshez@math.huji.ac.il>
Tue, 21 Nov 2000 16:22:25 +0200 (IST)


On Tue, 21 Nov 2000, Remco Gerlich wrote:

> I would write it like this:
> 
> import math
> 
> def factors(n, highestsofar=2):
>    for i in range(highestsofar, math.sqrt(n)+1):
>       if n % i == 0:
>          return [i] + factors(n/i, i)
>    return [n]

def factors(n, highestsofar=2, factorssofar=None):
	if factorssofar is None:
		factorssofar = []
	for i in range(highestsofar, math.sqrt(n)+1):
		if n % i == 0:
			factorssofar.append(i)
			return factors(n/i, i, factorssofar)
	factorssofar.append(n)
	return factorssofar

Is more efficient, and almost as clear.

--
Moshe Zadka <moshez@math.huji.ac.il> -- 95855124
http://advogato.org/person/moshez