Factorial - how did you complete it?


#1

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:
        numlist.append(x)
        x -= 1
    total = 1
    for i in range(0, len(numlist)):
        total *= numlist[i]
    return total


#2

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

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


#3

Here is an alternate solution

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

#4

This is what i did:

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

it worked.


#5

A recursive example is missing here.

Python Recursion: Factorial

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

Reads simply enough.

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


#6

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


#7

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
    else:
        return num * factorial(num - 1)

#8

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


#9

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:


#10

I don't understand how this continue to loops?