0

I am try to convet this function by creating it as a for or while loop, but having trouble.

def fact(n):
   if n<= 1:
       return 1
   else:
       return (n)*(fact(n-1))

this is what I attempted:

def fact(n):
   while n <= 1:
       return 1
   else:
       return (n)*(fact(n-1))
  • Please see [what is wrong with my factorial code in python](http://stackoverflow.com/q/28475637/4014959) for a variety of ways to compute factorials in Python. [My answer](http://stackoverflow.com/a/28477818/4014959) to that question provides timing stats for the various approaches. – PM 2Ring Apr 19 '15 at 08:03

3 Answers3

2

Converting the above recursive program to use loops is not as simple as changing an if to a while.

def fact(n):
    result = 1
    while n >= 1:
        result = result * n
        n = n - 1
    return result
Vaibhav Sagar
  • 2,208
  • 15
  • 21
1

If you're using a loop, you shouldn't be recursing, you should just multiply within the loop.

def fact(n):
    result = 1
    while n > 1:
        result *= n
        n = n - 1
    return result
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    There is no decrement operator in python (`--`). Change this to `n -= 1`. –  Apr 19 '15 at 07:57
  • You **can** have an `else:` on a `while` loop in Python! It's not used much, and is only useful if you have a `break`. – cdarke Apr 19 '15 at 07:58
  • You _can_ have an `else` clause on a `while` block, but it's not required here. See [The while statement](https://docs.python.org/3/reference/compound_stmts.html#the-while-statement) in the Python docs. – PM 2Ring Apr 19 '15 at 07:58
0

Using a for-loop:

result = 1
for v in xrange(1, n + 1):
    result *= v
return result

Using comprehension:

from operator import mul
return reduce(mul, xrange(1, n + 1), 1)
smac89
  • 39,374
  • 15
  • 132
  • 179