Factorial - was my approach too simple?


#1

Hello

I read the instructions and went with this -

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

Reading some of the other posts - https://discuss.codecademy.com/t/5-factorial/59777/4, https://discuss.codecademy.com/t/5-factorial/59479.

I was confident when I got my green bookmark

but now after reading the above, doubt set in.

Somehow my approach seems too simple, I do not know if others have experienced this. You go with your gut and then get overwhelmed by different words like - 'for' 'while' 'loops'.

These lessons are part of 'Practice Makes Perfect'. I know there is more then one way to achieve the results.
Was the aim to achieve the answer using specifically - for,while?


#2

What you did is a technique called recursion. It calls upon the function in the function with a change in the input. It is known to be more costly than loops (but sometimes, it's better to use recursion) for Python. So if you want to optimize performance in Python, I'd suggest loops.

Some languages have loops being more expensive than recursion (eg. Scheme/Racket).

Also, Pracitce Makes Perfect encourages the coders to use concepts already taught. Recursion was never taught so that is another point to stick with loops/concepts from previous lessons.


#3

No plan was specified but we are encouraged to work out algorithms and not use built-ins. Recursion is not taught here since it is a more advanced topic that cannot be treated lightly.

The iterative approach can use for or while. It's our choice. The example you linked to has a line,

# set up the loop

I left that line as it is to indicate that either can be used.

for n in range(2, x + 1):

or

while x > 1:
    # code
    x -= 1

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.