karlakmkj

Factorial recursion

Jan 5th, 2021 (edited)
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. #Usual recursive function for calculating factorial
  2. def factorial(n):
  3.     if n == 1:
  4.         return 1
  5.     else:
  6.         return n * factorial(n - 1)
  7.  
  8. print("5! is", factorial(5))
  9. print("10! is", factorial(10))
  10.  
  11. '''
  12. Another version to see what is happening with print statements in the conditions.
  13. Notice in the output how the execution climbs down the ladder from the original value of n to 1, then climbs back up the latter from 1 to n.
  14. '''
  15. def factorial(n):
  16.     if n == 1:
  17.         print("Base case reached!")
  18.         return 1
  19.    
  20.     else:
  21.         print("Finding ", n, " * ", n-1, "!", sep = "")
  22.         result = n * factorial(n - 1)  #since it calls back the same function it goes to if condition again then to this else
  23.         print(n, " * ", n-1, "! = ", result, sep = "") #after we got return 1, it comes back to this line to calculate the result
  24.         return result
  25.    
  26. print("5! is", factorial(5))
  27.  
  28. '''
  29. Output will show:
  30. Finding 5 * 4!
  31. Finding 4 * 3!
  32. Finding 3 * 2!
  33. Finding 2 * 1!
  34. Base case reached!
  35. 2 * 1! = 2
  36. 3 * 2! = 6
  37. 4 * 3! = 24
  38. 5 * 4! = 120
  39. 5! is 120
  40. '''
Add Comment
Please, Sign In to add comment