[Tutor] exercise is recursion
D-Man
dsh8290@rit.edu
Tue, 21 Nov 2000 09:50:35 -0500
On Tue, 21 Nov 2000 09:22:25 Moshe Zadka wrote:
| 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.
|
Why not
def factors( n , highestsofar=2 , factorssofar=[] ) :
...
Then when the client calls it
result = factors( number , factorssofar=[] )
The list will be empty. One less arg to pass in the recursion and also removes
the need for the "if ( factorssofar == None )" check. (I know the default arg
is only evaluated once, but that can be useful in this case)
| --
| Moshe Zadka <moshez@math.huji.ac.il> -- 95855124
| http://advogato.org/person/moshez
|
Does python do tail-recursion yet? If so, then Moshe's is definitely more
efficient (read better). If not, I think the previous solution is easier to
read, but both are quite clear.
Just my $0.02.
-D