Skip to content

Instantly share code, notes, and snippets.

@omeroot
Last active October 22, 2015 14:46
Show Gist options
  • Save omeroot/7219f1e93a5698156447 to your computer and use it in GitHub Desktop.
Save omeroot/7219f1e93a5698156447 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
# ________________________
# | Recursion |
# |________________________|
#
# |---Illustrative Examples
# | |
# | |__factorial function
#
#
#
# │ ▲ ┌───────────────┐
# │ ┌─┘ │return 4*6 = 24│
# │ │ └─────────.─────┘
#┌────────────▼──────────────┤ .
#│ factorial(4) │◀─┐ .....
#└────────────┬──────────────┘ │┌─────────────.─┐
# │ ┌──┘│return 3*2 = 6 │
#┌────────────▼──────────────┤ └─────────.─────┘
#│ factorial(3) │◀─┐ .....
#└────────────┬──────────────┘ │┌─────────────.─┐
# │ ┌──┘│return 2*1 = 2 │
#┌────────────▼──────────────┤ └─────────.─────┘
#│ factorial(2) │◀─┐ .....
#└────────────┬──────────────┘ │┌─────────────.─┐
# │ ┌──┘│return 1*1 = 1 │
#┌────────────▼──────────────┤ └─────────.─────┘
#│ factorial(1) │◀─┐ ..
#└────────────┬──────────────┘ │┌────────.─┐
# │ ┌──┘│ return 1 │
#┌────────────▼──────────────┤ └──────────┘
#│ factorial(0) │
#└───────────────────────────┘
#no circularity because each time function is invoked
#its argument is smaller by one, and when a base case is reached, no further recursive calls are made.
def __factorial(n):
if(n == 0):
return 1
return n * __factorial(n - 1) # n * ( factorial(n-1) )--> (n -1) * factorial(n-2) ...
if __name__ == "__main__":
print __factorial(5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment