# Re: please i need explanation

Discussion in 'Python' started by Jussi Piitulainen, Jan 11, 2013.

1. ### Jussi PiitulainenGuest

writes:
> 11.01.2013 17:35, 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.)

(real) numbers outside its intended domain (negative integers and
non-integers are outside). Not a good idea. (My version will loop
good. Caller beware.
Jussi Piitulainen, Jan 11, 2013

2. ### Thomas RachelGuest

Am 11.01.2013 17:33 schrieb :

>> def factorial(n):
>> if n<2:
>> return 1
>> f = 1
>> while n>= 2:
>> f *= n
>> f -= 1
>> return f
>>
>>
>>

I doubt this.

If you give n = 4, you run into an endless loop.

> but donâ€™t get why the return 1 and the code below.

The "if n < 2: return 1" serves to shorten the calculation process
below. It is redundant, as you have a "f = 1" and a "return f" for n < 2.

The code below first sets f, which holds the result, to 1 and then
multiplies it by n in each step. As the loop should contain a 'n -= 1',
n decreases by 1 every step, turning it into f = n * (n-1) * (n-2) * ...
* 2 and then, as n is not >= 2 any longer, stops the loop, returning f.

HTH,

Thomas
Thomas Rachel, Jan 11, 2013

3. ### Guest

-----Original Message-----
From: K. Elo
Sent: Friday, January 11, 2013 3:56 AM
To:
Subject: Re: please i need explanation

Hi!

Since there is no stated question, I need to guess:

n -= 1 (instead of "f -= 1")

should work.

Or maybe the question was a totally different one...

-Kimmo

11.01.2013 17:35, 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.
, Jan 11, 2013