please i need explanation
Jussi Piitulainen
jpiitula at ling.helsinki.fi
Fri Jan 11 13:20:31 CET 2013
kwakukwatiah at gmail.com writes:
> 11.01.2013 17:35, kwakukwatiah at gmail.com wrote:
> > def factorial(n):
> > if n<2:
> > return 1
> > f = 1
> > while n>= 2:
> > f *= n
> > f -= 1
> > return f
>
> please it works.but don’t get why the return 1 and the code below.
Ignoring the error that has been pointed out, this code seems to be
"optimized" to avoid multiplication by 1. I doubt if the difference is
measurable. If anyone cares enough to measure:
def fast_factorial(n):
if n < 2: return 1
f = 1
while n > 1:
f *= n
n -= 1
return f
def slow_factorial(n):
f = 1
while n != 0:
f *= n
n -= 1
return f
(Untested, and just kidding. For fast factorial routines, search for a
paper by Richard Fateman on the web. They're in Common Lisp, but the
branching techniques should be generally applicable.)
Additionally, your code produces nonsense quietly when called with
(real) numbers outside its intended domain (negative integers and
non-integers are outside). Not a good idea. (My version will loop
indefinitely instead. Better than a wrong answer but also not very
good. Caller beware. :)
More information about the Python-list
mailing list