Skip to content

Instantly share code, notes, and snippets.

@mofas
Created November 22, 2018 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mofas/3beff2a6691ca129d9a3f5675b11bc88 to your computer and use it in GitHub Desktop.
Save mofas/3beff2a6691ca129d9a3f5675b11bc88 to your computer and use it in GitHub Desktop.
Explain the iteration and recursion for beginner
def fact1(n):
acc = 1
for i in range(n):
# print(acc, i + 1)
acc *= (i + 1)
return acc
def fact2(n):
return 1 if n == 1 else n * fact2(n - 1)
print(fact1(5))
# 120 = 1 * 2 * 3 * 4 * 5
print(fact2(5))
# fact2(5) = 5 * fact2(4)
# = 5 * 4 * fact2(3)
# = 5 * 4 * 3 * fact2(2)
# = 5 * 4 * 3 * 2 * fact2(1)
# = 5 * 4 * 3 * 2 * 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment