Last active
March 16, 2017 15:41
-
-
Save lotka/2ca2c205fd96c888081d76365d116a81 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"# Recursive solution" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 50, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"0 1 1 2 3 5 8 13 21 34\n" | |
] | |
} | |
], | |
"source": [ | |
"def fib_recursive(n):\n", | |
" if n == 0:\n", | |
" return n\n", | |
" elif n <= 2:\n", | |
" return 1\n", | |
" else:\n", | |
" return fib_recursive(n-1) + fib_recursive(n-2)\n", | |
"\n", | |
"# Print first 10 numbers in fibonnaci sequence\n", | |
"for i in xrange(10):\n", | |
" print fib_iterative(i)," | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"# Iterative solution" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 54, | |
"metadata": { | |
"collapsed": false | |
}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"0 1 1 2 3 5 8 13 21 34\n" | |
] | |
} | |
], | |
"source": [ | |
"def fib_iterative(n):\n", | |
" a,b = 1,0\n", | |
" for i in xrange(n):\n", | |
" a,b = b,a+b\n", | |
" return b\n", | |
" \n", | |
"# Print first 10 numbers in fibonnaci sequence\n", | |
"for i in xrange(10):\n", | |
" print fib_iterative(i)," | |
] | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"display_name": "Python 2", | |
"language": "python", | |
"name": "python2" | |
}, | |
"language_info": { | |
"codemirror_mode": { | |
"name": "ipython", | |
"version": 2 | |
}, | |
"file_extension": ".py", | |
"mimetype": "text/x-python", | |
"name": "python", | |
"nbconvert_exporter": "python", | |
"pygments_lexer": "ipython2", | |
"version": "2.7.10" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment