[Tutor] exercise is recursion

Remco Gerlich scarblac@pino.selwerd.nl
Tue, 21 Nov 2000 16:18:10 +0100


On Tue, Nov 21, 2000 at 09:50:35AM -0500, D-Man wrote:
> 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)

That's a common gotcha, the [] is only evaluated once, when the function
is defined.

That means that if you call the function more than once, factorssofar will
not be an empty list anymore, since you changed it! Don't see how that
is useful.

Moshe's factorssofar=None (and then set it to [] if still None) is the
standard workaround.

> 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.

Python does tail recursion just fine, just not tail recursion *optimization*
;-)

-- 
Remco Gerlich