Factorial - how did you complete it?


How did everyone else complete this exercise. I ended up with the code below, but it doesn't feel quite right even though it gives the right answer!!

def factorial(x):
    numlist = []
    while x > 0:
        x -= 1
    total = 1
    for i in range(0, len(numlist)):
        total *= numlist[i]
    return total


Why not just for i in range(0, x); & total *= i?

Edit: I meant for i in range(1, x + 1):


Here is an alternate solution

def factorial(x):
    total = 1
    for counter in range(1, x + 1):
        total *= counter
    return total


This is what i did:

def factorial(x):
   r = 1
   while x - 1 > 0:
       r *= x 
       x -= 1
   return r

it worked.


A recursive example is missing here.

Python Recursion: Factorial

factorial = lambda num: 1 if (num < 1) else num * factorial(num-1)
# OUTPUT: 24
# OUTPUT: 3628800

Reads simply enough.

Return 1 if the num is less than 1 else return num * (num - 1)


def factorial(x):
if x == 0 or x == 1:
return 1
return x * factorial(x-1)


For those not familiar with lambda expressions (borrowed from functional programming languages like Haskell), here is a python function that is equivalent

def factorial(num):
    if (num < 1):
        return 1
        return num * factorial(num - 1)


Guys, its too simple using the features of math module, like this:

import math
def factorial(x):
x = math.factorial(x)
return x
print factorial(4)

the print is for testing purpose


Thank you all, some interesting responses here. I needed to think about some of the responses to figure out how they would work, so it has been educational.

Not sure I agree on the use of the math module; whilst it gives the correct answer, the point of the exercise is the process by which you manage to arrive at it surely? :slight_smile:


I don't understand how this continue to loops?