0 points
Submitted by Giacomo Sorbi
over 8 years

1.5 Recursive Factorial - just one line of code and a single variable: can you do better ;)?

Well, one line except the definition:

def factorial(x):
    return x*factorial(x-1) if x>1 else 1

For the use of the ternary operator in python, also see this.

Putting it all on the same line gives me an error, yet the exercise passes.

I was wondering if CPU-wise is better to use recursive function or instead to use some support variable and a loop: any idea?

Edit: a pro friend of mine told me just now that in Python a recursive statement tends to be heavier as in this case the calls would remain in the stack. Quite a burden for larger numbers.

Answer 514a033fb509068a73000712

3 votes


very interesting. Like it

Submitted by Srav
over 8 years


Giacomo Sorbi over 8 years

Thanks for your kind feed :)

CAD over 8 years

recursion often is easier to understand and code, the more elegant way, if you will, but in most cases is dangerous if the function calles itself to often due to the possibility of stack overflow…

Answer 514b2a61c9fe0c721d000101

2 votes


Again Giacomo, not as elegant as you. Just happy I figured it out without using the hint or anything. Im only on day 8 of any programming at all so im just happy to get it lol.

def factorial(x):
    for i in reversed(range(x)):
        if i == 0:
            return x
            x *= int(i)
Submitted by David Corn
over 8 years

Answer 514cbac08f904a789d00033b

1 vote


def factorial(num):return reduce(lambda x,y:x*y,[1]+range(1,num+1))

Although this is not the best..but simple oneliner… Version-2

fac = lambda num:[1,0][num>0] or fac(num-1)*num
Submitted by cybercam
over 8 years