Practice Makes Perfect 5/15

#1

I'm confused as to why we need to write the 'else' on this section:

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

#2

Yes, what does any of it mean? What is the purpose of learning it? What does it do?
Why are we adding the initial return result ourselves? Why does the console print out 'none'.
Why has this course dumped me at the 60% mark? Is Python mainly for maths brains? What DOES the else part signify or do?

#3

def factorial(n):
----total = 1
----while n > 0:
--------total = total * n
--------n = n - 1
print factorial(10)

#4

sorry, I cheated.

``````def factorial(x):
import math
return math.factorial(x)``````

#5

def factorial(x):
z = 1
for y in range(x):
z *= y+1
return z

#6

could you please explain why you added instead of subtracted from y?

#7

y is a local variable which ranges between 0 to x(No. who's factorial is calculated),
So if start from 0, the answer will be 0 only and we'll traverse up to X-1 only (as in for loop the count starts from 0 only).

So I've added 1 for every iteration so that we'll go as a sequence of 1*2*3*4....x,
rather than 0*1*2*3...x-1

#8

That's a recursive solution to the problem. Basically, it splits itself between the base case and the inductive (recursive) case. That first part covers the scenario in which the user inputs 0, which returns 1 for a factorial but also serves to stop the recursive solution.

Take x = 3 for example. The program will run through to the end and get 3 * factorial(2). It will then run through the same function for 2 and get 2 * factorial(1). That will run through and get 1 * factorial(0). That last part meets the base case so it will stop and return 1, which will then be multiplied by 2, and then be multiplied by 3.

Not sure if this is kosher to link to other sites, but here is a good MIT lecture on recursion that covers this pretty well:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00sc-introduction-to-computer-science-and-programming-spring-2011/unit-1/lecture-6-recursion/

#9

Well, that worked for me. Thanks for stopping me form pulling my hair out!