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
2 comments
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…
Answer 514b2a61c9fe0c721d000101
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)
Popular free courses
- Free course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner Friendly4 Lessons - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly11 Lessons - Free course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner Friendly6 Lessons