Skip to content

Instantly share code, notes, and snippets.

@manisnesan
Created August 4, 2014 00:49
Show Gist options
  • Save manisnesan/599d40a3a64491a9192a to your computer and use it in GitHub Desktop.
Save manisnesan/599d40a3a64491a9192a to your computer and use it in GitHub Desktop.
Three different ways to compute fibonacci
#!/usr/bin/env python
def fib_iterative(n):
a,b = 1,1
for i in range(n - 1):
a,b = b,a+b
return a
def fib_recursive(n):
if (n == 1 or n == 2 ):
return 1
else:
return fib_recursive(n-1) + fib_recursive(n - 2)
def fib_recursive_tail(n):
def fib_aux(a, b, n):
return fib_aux(b, a+b, n-1) if n > 1 else a
return fib_aux(1, 1, n)
def main ():
print fib_iterative(5)
print fib_recursive(5)
print fib_recursive_tail(5)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment