Python is not bad ;-)

Dave Angel davea at davea.name
Sat May 2 06:35:11 EDT 2015


On 05/02/2015 05:33 AM, Cecil Westerhof wrote:

Please check your email settings.  Your messages that you type seem to 
be indented properly, but those that are quoting earlier messages (even 
your own) are not.  See below.  I suspect there's some problem with how 
your email program processes html messages.

> Op Saturday 2 May 2015 10:26 CEST schreef Cecil Westerhof:
>>
>> That is mostly because the tail recursion version starts multiplying
>> at the high end. I wrote a second version:
>> def factorial_tail_recursion2(x):
>> y = 1
>> z = 1
>> while True:
>> if x == z:
>> return y
>> y *= z
>> z += 1
>>
>> This has almost the performance of the iterative version: 34 and 121
>> seconds.
>>
>> So I made a new recursive version:
>> def factorial_recursive(x, y = 1, z = 1):
>> return y if x == z else factorial_recursive(x, x * y, z + 1)
>
> Stupid me 'x == z' should be 'z > x'
>

I can't see how that is worth doing. The recursive version is already a 
distortion of the definition of factorial that I learned.  And to force 
it to be recursive and also contort it so it does the operations in the 
same order as the iterative version, just to gain performance?

If you want performance on factorial, write it iteratively, in as 
straightforward a way as possible.  Or just call the library function.

Recursion is a very useful tool in a developer's toolbox.  But the only 
reason I would use it for factorial is to provide a simple demonstration 
to introduce the concept to a beginner.


-- 
DaveA



More information about the Python-list mailing list