Created
April 6, 2015 19:03
-
-
Save sk187/7c92364addbe262f6552 to your computer and use it in GitHub Desktop.
Python Recursion Factorial Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Recursion can be difficult for beginners. It still is difficult for me. | |
The best way to improve is to try "easy" recursion problems such as | |
factorials in this case. | |
Instructions: | |
Create a function that takes an positive interger and returns the factorial of it | |
Example factorial(3) should return 3*2*1 or 6 | |
Factorial(1) should return 1 | |
Factorial(0) should return 1 | |
''' | |
#Non Recursion Example | |
def factorial(x): | |
total = 1 | |
if x == 0 or x == 1: # Handles Edge Case of 1 or 0 | |
return total | |
while x > 1: | |
total = total * x # Multiples variable total defined outside of loop with x | |
x-=1 # Subtracts one from x so that the while loop will break when x = 1 | |
return total | |
# Recursion Example | |
def factorial(x): | |
if x == 0 or x ==1: # When x is equal to 0 or 1, it returns 1 | |
return 1 | |
return x * factorial(x-1) # multiples x with the recursion or calling itself with x - 1 | |
''' | |
If we do factorial (3) | |
It first checks if x is == 0 or x == 1 => False | |
Then it go to x * factorial(x-1) which would be 3 * factorial(2) | |
Evaluate factorial(2) | |
Check if x == 0 or x == 1 => False | |
x * factorial(x-1) or 2 * factorial(1) | |
Evaluates factorial(1) | |
Check if x == 0 or x == 1 => True | |
returns 1 | |
factorial(1) evaluates to 1 | |
returns 1 | |
So 2 * factorial(1) = 2 * 1 => 2 | |
factorial(2) evaluates to 2 | |
returns 2 | |
So factorial(2) = 2 | |
So 3 * factorial(2) = 3 * 2 => 6 | |
This function then returns 6 | |
''' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment