[Tutor] Problem with python
Emmanuel Ruellan
emmanuel.ruellan at laposte.net
Wed Oct 20 01:26:46 CEST 2010
On Tue, Oct 19, 2010 at 11:02 PM, Matthew Nunes <matthewnunes at hotmail.com>wrote:
>
> It wrote a piece of code for the factorial function in math for example 3!
> is 3 * 2 * 1. I cannot understand the how it claimed the code executed, and
> logically it makes no sense to me.
>
>
I suggest you follow the algorithm yourself, with a pencil and a sheet of
paper. Substitute various numerical values for n, starting with zero.
For example:
For n=0, the body of the function becomes:
if 0 == 0:
return 1
else:
recurse = factorial(0-1)
result = 0 * recurse
return result
What result do you get?
For n=1, it gets a little bit tricky, because the function calls itself:
if 1 == 0:
return 1
else:
recurse = factorial(1-1)
result = 1 * recurse
return result
You'd like an easier method to calculate factorials?
>>> from math import factorial
>>> print factorial(4)
24
--
Emmanuel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20101020/d2e44aeb/attachment-0001.html>
More information about the Tutor
mailing list