Skip to content

Instantly share code, notes, and snippets.

@lotka
Last active March 16, 2017 15:41
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 lotka/2ca2c205fd96c888081d76365d116a81 to your computer and use it in GitHub Desktop.
Save lotka/2ca2c205fd96c888081d76365d116a81 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"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