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.

very interesting. Like it

points
Submitted by Srav
over 8 years

Giacomo Sorbi over 8 years

Thanks for your kind feed :)

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…

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
else:
x *= int(i)
points
Submitted by David Corn
over 8 years