Skip to content

Instantly share code, notes, and snippets.

@obikag
Created February 25, 2015 00:29
Show Gist options
  • Save obikag/04664177857916e63c04 to your computer and use it in GitHub Desktop.
Save obikag/04664177857916e63c04 to your computer and use it in GitHub Desktop.
Fibonacci Number methods done in Python. First two methods calculates the Fibonacci number (n), while the last method prints the Fibonacci number sequence 'n' times.
'''
Created on Feb 24, 2015
'''
# Recursive Method calculating Fibonacci Number for n
def fibRecursion(n):
if (n == 0) :
return 0
elif (n == 1):
return 1
else:
return fibRecursion(n-1) + fibRecursion(n-2)
# Method containing a Loop that calculates Fibonacci Number for n
def fibLoop(n):
if (n == 0):
return 0
elif ((n == 1) or (n == 2)) :
return 1
else:
fib1, fib2, fib = 1, 1, 1
i = 3
while (i < (n+1)):
fib = fib1 + fib2
fib1 = fib2
fib2 = fib
i += 1
return fib
# Method that prints Fibonacci Number sequence n times
def fibSequence(n):
if (n < 0):
return 'Input must be a positive Number'
else:
results = ''
for i in range(0,n):
if (i == n-1) :
results = results +str(fibRecursion(i))
else :
results = results +str(fibRecursion(i))+', '
return 'Fibonacci Sequence of the first '+str(n)+' numbers is '+str(results)
# Test Section
print('Recurssion; fib(10): '+str(fibRecursion(10))) # 55
print('Loop; fib(10): '+str(fibLoop(10))) # 55
print(fibSequence(10)) # Fibonacci Sequence of the first 10 numbers is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment