Commit 4cc2512a authored by HermesTheDev's avatar HermesTheDev

Recusion Examples

parent 5dd6e52b
#Example #1 - Basic Example (5*4*3*2*1=120)
def factorial(x):
if x == 1:
return 1
else:
return x * factorial(x-1)
print(factorial(5))
##########################################################################################
#Commented Out to Not Cause Errors in the Third Example
#Example #2 - Runs Out of Memory and Thus Returns Error
#def factorial(x):
#return x * factorial(x-1)
#print(factorial(5))
##########################################################################################
#Example #3 Determines Whether a Number is Even or Odd (Plucking Petals From a Flower)
def is_even(x):
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
return not is_even(x)
print(is_odd(2))
print(is_even(3))
##########################################################################################
#Example #4 with Fib
def fib(x):
if x == 0 or x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
print(fib(4))
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment